package com.xhsj.user.sms.process.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xhsj.user.event.event.MessageEvent;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.lsm.entity.TbContractApply;
import com.xhsj.user.lsm.service.TbContractApplyService;
import com.xhsj.user.sms.process.dto.StartProcessDto;
import com.xhsj.user.sms.process.entity.*;
import com.xhsj.user.sms.process.mapper.TbPurchaseProcessHiTaskMapper;
import com.xhsj.user.sms.process.mapper.TbPurchaseProcessTaskMapper;
import com.xhsj.user.sms.base.BaseService;
import com.xhsj.user.sms.process.vo.SaveOrderSubTaskVo;
import com.xhsj.user.sms.purchase.entity.*;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseOrderMapper;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseOrderSubtaskMapper;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseTerminationContractApplyMapper;
import com.xhsj.user.sms.purchase.query.*;
import com.xhsj.user.sms.purchase.service.*;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.Message;
import com.xhsj.user.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;


/**
 * 任务表 服务实现类
 *
 * @author suxiaolin
 * @since 2020-03-16
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class TbPurchaseProcessTaskService
        extends BaseService<TbPurchaseProcessTaskMapper, TbPurchaseProcessTask> {
    @Autowired
    private TbPurchaseProcessTaskMapper dao;

    @Autowired
    private TbGlobalUserService tbGlobalUserService;

    @Autowired
    private TbGlobalUserMapper tbGlobalUserMapper;

    @Autowired
    private TbPurchaseProcessNodeService tbPurchaseProcessNodeService;

    @Autowired
    private TbPurchaseProcessHiTaskService tbPurchaseProcessHiTaskService;

    @Autowired
    private TbPurchaseProcessOpinionService tbPurchaseProcessOpinionService;

    @Autowired
    private TbPurchaseProcessOpinionFileService tbPurchaseProcessOpinionFileService;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private TbPurchaseApplyService tbPurchaseApplyService;

    @Autowired
    private TbPurchaseSubtaskPaymentApplyService tbPurchaseSubtaskPaymentApplyService;
    //订单其他文件
    @Autowired
    TbPurchaseSubtaskOtherFileService tbPurchaseSubtaskOtherFileService;
    // 支付记录
    @Autowired
    TbPurchaseSubtaskPaymentRecordService tbPurchaseSubtaskPaymentRecordService;

    @Autowired
    private TbPurchaseOrderService tbPurchaseOrderService;

    @Autowired
    private TbPurchaseOrderSubtaskService tbPurchaseOrderSubtaskService;

    @Autowired
    private TbPurchaseOrderSubtaskMapper tbPurchaseOrderSubtaskMapper;

    @Autowired
    private TbPurchaseOrderMapper tbPurchaseOrderMapper;

    @Autowired
    private TbPurchaseOrderGoodsService tbPurchaseOrderGoodsService;

    //采购订单-采购相关文件
    @Autowired
    private TbPurchaseOrderFileService tbPurchaseOrderFileService;

    //质检记录表
    @Autowired
    private TbPurchaseSubtaskQualityRecordService tbPurchaseSubtaskQualityRecordService;

    //质检记录文件表
    @Autowired
    private TbPurchaseSubtaskQualityRecordFileService tbPurchaseSubtaskQualityRecordFileService;

    @Autowired
    private TbPurchaseSubtaskStorageRecordService tbPurchaseSubtaskStorageRecordService;

    @Autowired
    private TbPurchaseSubtaskReturnRecordService tbPurchaseSubtaskReturnRecordService;

    @Autowired
    private TbPurchaseSubtaskReturnRecordFileService tbPurchaseSubtaskReturnRecordFileService;

    //终止合同记录
    @Autowired
    private TbPurchaseTerminationContractApplyMapper tbPurchaseTerminationContractApplyMapper;

    @Autowired
    private TbPurchaseTerminationContractApplyService tbPurchaseTerminationContractApplyService;

    //终止合同记录文件
    @Autowired
    private TbPurchaseTerminationContractApplyFileService tbPurchaseTerminationContractApplyFileService;

    @Autowired
    private TbPurchaseApplyFileService tbPurchaseApplyFileService;

    //采购申请清单表
    @Autowired
    private TbPurchaseApplyListService tbPurchaseApplyListService;

    @Autowired
    private TbPurchaseProcessHiTaskMapper tbPurchaseProcessHiTaskMapper;

    @Autowired
    private TbPurchaseSubtaskStorageRecordFileService tbPurchaseSubtaskStorageRecordFileService;

    @Autowired
    private TbPurchaseTaskService tbPurchaseTaskService;

    @Autowired
    private TbPurchaseSubtaskListService tbPurchaseSubtaskListService;

    @Autowired
    public TbPurchaseSubtaskStatementService tbPurchaseSubtaskStatementService;

    @Autowired
    private TbContractApplyService tbContractApplyService;

    //角色名称 总经理
    @Value("${rolekeyname.generalManager}")
    private String roleNameTwo;

    //角色名称 采购经理
    @Value("${rolekeyname.purchaseManager}")
    private String roleNameThree;

    //仓管经理
    @Value("${rolekeyname.warehouseManager}")
    private String warehouseManager;

    //角色名称 财务主管
    @Value("${rolekeyname.financialManager}")
    private String financialManager;

    //品质经理
    @Value("${rolekeyname.qualityManager}")
    private String qualityManager;


    /**
     * 启动流程
     *
     * @author 苏小林
     * @date 2020/3/17 9:51
     * @param: entity
     * @return: boolean
     */
    public String startProcess(StartProcessDto startProcessDto) throws Exception {
        String createBy = startProcessDto.getCreateBy();
        String dataId = startProcessDto.getDataId();
        String type = startProcessDto.getProcessType();
        Object userId = startProcessDto.getUserId();
        Object roleIds = startProcessDto.getRoleIds();
        String dealWith = startProcessDto.getStatus();
        if (StringUtils.isBlank(type)) {
            type = "1";
        }
        Map<String, Object> resultData = new HashMap<>();
        String nodeName = "";

        try {
            // 查询初始流程节点
            TbPurchaseProcessNode firstNode = tbPurchaseProcessNodeService.getFirstNode(StringUtils.toInteger(dealWith), type);

            // 创建人历史任务
            TbPurchaseProcessHiTask cjrTbPurchaseProcessHiTask =
                    new TbPurchaseProcessHiTask(
                            String.valueOf(createBy),
                            String.valueOf(dataId),
                            firstNode.getNodeId(),
                            0,
                            String.valueOf(createBy),
                            String.valueOf(createBy),
                            String.valueOf(type));
            Date date = new Date(System.currentTimeMillis() - 1000);
            cjrTbPurchaseProcessHiTask.setCreateDate(date);
            cjrTbPurchaseProcessHiTask.setUpdateDate(date);
            boolean cjrSave = tbPurchaseProcessHiTaskService.save(cjrTbPurchaseProcessHiTask);
            if (!cjrSave) {
                log.error("启动流程失败,任务启动过程中有返回结果为0的");
                throw new Exception("启动流程失败");
            }
            List<TbPurchaseProcessTask> list = Lists.newArrayList();
            if (!Objects.isNull(userId)) {
                List<String> split = JSONArray.parseArray(String.valueOf(userId), String.class);
                for (String s : split) {
                    TbPurchaseProcessTask tbPurchaseProcessTask = new TbPurchaseProcessTask(
                            s,
                            "",
                            "",
                            String.valueOf(dataId),
                            firstNode.getNextNodeId(),
                            String.valueOf(createBy),
                            String.valueOf(createBy),
                            String.valueOf(type));
                    boolean saveTask = this.save(tbPurchaseProcessTask);
                    if (!saveTask) {
                        log.error("保存数据失败");
                        throw new Exception("保存数据失败");
                    }
                    list.add(tbPurchaseProcessTask);
                }
            }

            // 角色
            if (!Objects.isNull(roleIds)) {
                List<String> split1 = JSONArray.parseArray(String.valueOf(roleIds), String.class);
                for (String s : split1) {
                    // 添加正在执行任务
                    TbPurchaseProcessTask tbPurchaseProcessTask =
                            new TbPurchaseProcessTask(
                                    "", s, "", String.valueOf(dataId),
                                    firstNode.getNextNodeId(),
                                    String.valueOf(createBy),
                                    String.valueOf(createBy),
                                    String.valueOf(type));
                    boolean saveTask = this.save(tbPurchaseProcessTask);
                    if (!saveTask) {
                        log.error("保存数据失败");
                        throw new Exception("保存数据失败");
                    }
                    list.add(tbPurchaseProcessTask);
                }
            }

            for (TbPurchaseProcessTask tbPurchaseProcessTask : list) {
                // 添加下一节点任务到历史任务
                TbPurchaseProcessHiTask tbPurchaseProcessHiTask = new TbPurchaseProcessHiTask();
                BeanUtils.copyProperties(tbPurchaseProcessTask, tbPurchaseProcessHiTask);
                tbPurchaseProcessHiTask.setStatus(2);
                tbPurchaseProcessHiTask.setUserId(String.valueOf(createBy));

                int insert = tbPurchaseProcessHiTaskMapper.insert(tbPurchaseProcessHiTask);

                if (insert > 0) {
                    String nextNodeId = firstNode.getNextNodeId();

                    Map<String, Object> nextNode = getNextNode(nextNodeId, 0, String.valueOf(type));

                    nodeName = String.valueOf(nextNode.get("currentName"));
                } else {
                    log.error("启动流程失败,任务启动过程中有返回结果为0的");
                    throw new Exception("启动流程失败");
                }
            }
            resultData.put("nodeId", firstNode.getNodeId());
        } catch (Exception e) {
            log.error("启动流程出错:{}", e);
            throw e;
        }
        resultData.put("nodeName", nodeName);
        return nodeName;
    }

    /**
     * 保存审核历史任务
     *
     * @author 苏小林
     * @date 2020/7/22 13:34
     */
    public void saveProcessHiTask(TbPurchaseProcessHiTask tbPurchaseProcessHiTask) throws Exception {
        tbPurchaseProcessHiTask.setId(IdGen.uuid());
        if (tbPurchaseProcessHiTask.getCreateDate() == null) {
            tbPurchaseProcessHiTask.setCreateDate(new Date());
            tbPurchaseProcessHiTask.setUpdateDate(new Date());
        } else {
            tbPurchaseProcessHiTask.setUpdateDate(tbPurchaseProcessHiTask.getCreateDate());
        }

        int insert = tbPurchaseProcessHiTaskMapper.insert(tbPurchaseProcessHiTask);
        if (insert == 0) {
            log.error("保存历史任务失败");
            throw new Exception("保存历史任务失败");
        }
    }

    private void startProcessByUserId(StartProcessDto startProcessDto) throws Exception {
        String createBy = startProcessDto.getCreateBy();
        String dataId = startProcessDto.getDataId();
        String type = startProcessDto.getProcessType();
        Object userId = startProcessDto.getUserId();
        if (StringUtils.isBlank(type)) {
            type = "1";
        }
        try {
            if (!Objects.isNull(userId)) {
                List<String> split = JSONArray.parseArray(String.valueOf(userId), String.class);
                for (String s : split) {
                    TbPurchaseProcessTask tbPurchaseProcessTask =
                            new TbPurchaseProcessTask(
                                    s,
                                    "",
                                    "",
                                    String.valueOf(dataId),
                                    startProcessDto.getNodeId(),
                                    String.valueOf(createBy),
                                    String.valueOf(createBy),
                                    String.valueOf(type));
                    boolean saveTask = this.save(tbPurchaseProcessTask);
                    if (!saveTask) {
                        log.error("保存数据失败");
                        throw new Exception("保存数据失败");
                    }

                    // 添加正在执行任务到历史任务
                    if (tbPurchaseProcessTask != null) {
                        TbPurchaseProcessHiTask tbPurchaseProcessHiTask = new TbPurchaseProcessHiTask();
                        BeanUtils.copyProperties(tbPurchaseProcessTask, tbPurchaseProcessHiTask);
                        tbPurchaseProcessHiTask.setStatus(2);// 未审核
                        tbPurchaseProcessHiTask.setUpdateDate(null);
                        tbPurchaseProcessHiTask.setUpdateBy("");
                        int insert = tbPurchaseProcessHiTaskMapper.insert(tbPurchaseProcessHiTask);
                        if (insert == 0) {
                            log.error("保存数据失败");
                            throw new Exception("保存数据失败");
                        }
                    }
                }
            }

        } catch (Exception e) {
            log.error("启动流程出错:{}", e);
            throw e;
        }
    }


    public String startContractProcess(Map<String, Object> map) throws Exception {
        Object createBy = map.get("createBy");
        Object dataId = map.get("dataId");
        Object type = map.get("processType");
        Object userId = map.get("proposerId");
        Object roleIds = map.get("roleIds");
        Object dealWith = map.get("status");
        Object proposerId = map.get("proposerId");
        if (Objects.isNull(type)) {
            type = "1";
        }
        String nodeName = "";
        try {
            // 查询初始流程节点
            TbPurchaseProcessNode firstNode = tbPurchaseProcessNodeService.getFirstNode(StringUtils.toInteger(dealWith), type);
            nodeName = firstNode.getNodeName();
            // 创建人历史任务
            TbPurchaseProcessHiTask cjrTbPurchaseProcessHiTask =
                    new TbPurchaseProcessHiTask(
                            String.valueOf(createBy),
                            String.valueOf(dataId),
                            firstNode.getNodeId(),
                            0,
                            String.valueOf(createBy),
                            String.valueOf(createBy),
                            String.valueOf(type));
            cjrTbPurchaseProcessHiTask.setCreateDate(new Date());
            cjrTbPurchaseProcessHiTask.setUpdateDate(new Date());
            boolean cjrSave = tbPurchaseProcessHiTaskService.save(cjrTbPurchaseProcessHiTask);
            if (!cjrSave) {
                log.error("启动流程失败,任务启动过程中有返回结果为0的");
                throw new Exception("启动流程失败");
            }

            TbPurchaseProcessTask tbPurchaseProcessTask = null;
            if (!Objects.isNull(userId)) {
                tbPurchaseProcessTask =
                        new TbPurchaseProcessTask(
                                String.valueOf(userId),
                                "",
                                "",
                                String.valueOf(dataId),
                                firstNode.getNodeId(),
                                String.valueOf(createBy),
                                String.valueOf(proposerId),
                                String.valueOf(type));
                boolean saveTask = this.save(tbPurchaseProcessTask);
                if (!saveTask) {
                    log.error("保存数据失败");
                    throw new Exception("保存数据失败");
                }
            }

            // 角色
            if (!Objects.isNull(roleIds)) {
                List<String> split1 = JSONArray.parseArray(String.valueOf(roleIds), String.class);
                for (String s : split1) {
                    // 添加正在执行任务
                    tbPurchaseProcessTask =
                            new TbPurchaseProcessTask(
                                    "", s, "", String.valueOf(dataId),
                                    firstNode.getNodeId(),
                                    String.valueOf(createBy),
                                    String.valueOf(proposerId),
                                    String.valueOf(type));
                    boolean saveTask = this.save(tbPurchaseProcessTask);
                    if (!saveTask) {
                        log.error("保存数据失败");
                        throw new Exception("保存数据失败");
                    }
                }
            }
            // 添加下一节点任务到历史任务
            TbPurchaseProcessHiTask tbPurchaseProcessHiTask = new TbPurchaseProcessHiTask();
            BeanUtils.copyProperties(tbPurchaseProcessTask, tbPurchaseProcessHiTask);
            tbPurchaseProcessHiTask.setStatus(2);
            tbPurchaseProcessHiTask.setUserId(String.valueOf(createBy));
            int insert = tbPurchaseProcessHiTaskMapper.insert(tbPurchaseProcessHiTask);
            if (insert < 0) {
                log.error("启动流程失败,任务启动过程中有返回结果为0的");
                throw new Exception("启动流程失败");
            }

        } catch (Exception e) {
            log.error("启动流程出错:{}", e);
            throw e;
        }
        return nodeName;
    }

    // 公共流程采购申请
    public boolean execProcess(SmsApprovalQuery data) throws Exception {
        // 修改采购申请节点和状态 1 保存 2 提交
        TbPurchaseTask tbPurchaseTask = new TbPurchaseTask();
        //流程
        if (data.getSubmitStatus() == 2) {
            Map<String, Object> mapParam = StringUtils.toJavaBean(data, Map.class);
            String s = this.handleAudit(mapParam);
            tbPurchaseTask.setNodeName(s);
        }
        tbPurchaseTask.setId(data.getDataId());
        tbPurchaseTask.setUpdateDate(new Date());
        tbPurchaseTask.setUpdateBy(data.getCreateBy());
        tbPurchaseTask.setSubmitStatus(data.getSubmitStatus());
        if (!tbPurchaseTaskService.updateById(tbPurchaseTask)) {
            log.error("修改采购申请提交状态失败");
            throw new Exception("修改采购申请提交状态失败");
        }
        return true;
    }


    // 公共流程采购订单
    public boolean execProcessOrder(PurchaseOrderQuerySms data) throws Exception {
        //流程
        String s = null;
        if (data.getSubmitStatus() == 2) {
            data.setProcessType("1");
            Map<String, Object> mapParam = JSON.parseObject(JSON.toJSONString(data), Map.class);
            s = this.handleAudit(mapParam);
        }
        // 审批意见及附件
//        this.execProcessOpinion(data);
        //修改采购订单的提交状态
        this.updatePurchaseOrderSubmitStatus(data, s);
        return true;
    }

    // 公共流程采购订单任务子任务
    public boolean execProcessOrderSubtask(PurchaseOrderQuerySms data) throws Exception {
        //流程
        String s = null;
        if (data.getSubmitStatus() == 2) {
            data.setProcessType("2");
            Map<String, Object> mapParam = JSON.parseObject(JSON.toJSONString(data), Map.class);
            s = this.handleAudit(mapParam);
        }
        //修改采购订单任务子任务的提交状态
        this.updatePurchaseOrderSubtaskSubmitStatus(data, s);
        return true;
    }

    // 公共流程终止合同
    public boolean execProcessContract(SmsApprovalQuery data) throws Exception {
        //流程
        String s = null;
        if (data.getSubmitStatus() == 2) {
            Map<String, Object> mapParam = JSON.parseObject(JSON.toJSONString(data), Map.class);
            s = this.handleAudit(mapParam);
            //修改终止合同节点
            this.updateContractNodeName(data.getDataId(), s, data.getCreateBy());
        }

        return true;
    }

    //关闭订单
//    public boolean execProcessEndOrder(EndOrderQuerySms data) throws Exception {
//        //流程
//        Map<String, Object> mapParam = JSON.parseObject(JSON.toJSONString(data), Map.class);
//        String  s = this.endOrderHandleAudit(mapParam);
//        //修改终止合同节点
//        if("3".equals(data.getProcessType())) {
//            data.setDataId(data.getDataId());
//            TbPurchaseTerminationContractApply tbPurchaseTerminationContractApply = new TbPurchaseTerminationContractApply();
//            tbPurchaseTerminationContractApply.setId(data.getDataId());
//            tbPurchaseTerminationContractApply.setNodeName(s);
//            if (tbPurchaseTerminationContractApplyMapper.updateById(tbPurchaseTerminationContractApply) != 1) {
//                log.error("修改终止合同节点失败");
//                throw new Exception("修改终止合同节点失败");
//            }
//            data.setDataId(data.getPurchaseOrderId());
//        }
//        //修改采购订单的提交状态
//        SmsApprovalQuery approvalQuery = StringUtils.toJavaBean(data, SmsApprovalQuery.class);
//        this.updatePurchaseOrderSubmitStatus(approvalQuery,s);
//        return true;
//    }

    //订单结束-合同
    public boolean endContractOrderApproval(CloseOrderQuery data) throws Exception {
        //保存终止合同回传文件
        data.setContractId(data.getDataId());
        TerminationContractReturnFileQuerySms terminationContractReturnFileQuery = StringUtils.toJavaBean(data, TerminationContractReturnFileQuerySms.class);
        this.saveReturnFile(terminationContractReturnFileQuery);
        //流程
        this.execProcessCloseContract(data);
        return true;
    }

    //公共关闭订单流程-合同
    public boolean execProcessCloseContract(CloseOrderQuery data) throws Exception {
        //流程
        Map<String, Object> mapParam = JSON.parseObject(JSON.toJSONString(data), Map.class);
        String s = this.closeContractOrderHandleAudit(mapParam);
        //修改终止合同节点
        if ("3".equals(data.getProcessType())) {
            this.updateContractNodeName(data.getDataId(), s, data.getCreateBy());
            data.setDataId(data.getPurchaseOrderId());
        }
        //修改采购订单任务子任务的提交状态
        SmsApprovalQuery smsApprovalQuery = StringUtils.toJavaBean(data, SmsApprovalQuery.class);
        this.updatePurchaseOrderSubtaskSubmitStatus(smsApprovalQuery, s);
        return true;
    }

    //修改合同申请的节点
    public boolean updateContractNodeName(String dataId, String nodeName, String userId) throws Exception {
        TbPurchaseTerminationContractApply tbPurchaseTerminationContractApply = new TbPurchaseTerminationContractApply();
        tbPurchaseTerminationContractApply.setId(dataId);
        tbPurchaseTerminationContractApply.setNodeName(nodeName);
        tbPurchaseTerminationContractApply.setUpdateDate(new Date());
        tbPurchaseTerminationContractApply.setUpdateBy(userId);
        if (tbPurchaseTerminationContractApplyMapper.updateById(tbPurchaseTerminationContractApply) != 1) {
            log.error("修改终止合同节点失败");
            throw new Exception("修改终止合同节点失败");
        }
        return true;
    }

    // 公共流程采购订单多人审批全部通过才能通过
    public boolean execProcessOrderAllPass(PurchaseOrderQuerySms data) throws Exception {
        //流程
        if (data.getSubmitStatus() == 2) {
            Map<String, Object> mapParam = JSON.parseObject(JSON.toJSONString(data), Map.class);
            String s = this.handleAuditAllPass(mapParam);
            // 修改采购申请节点
            if (StringUtils.isNotBlank(s)) {
                TbPurchaseApply tbPurchaseApply = new TbPurchaseApply();
                tbPurchaseApply.setNodeName(s);
                tbPurchaseApply.setId(data.getPurchaseTaskId());
                tbPurchaseApply.setUpdateDate(new Date());
                tbPurchaseApply.setUpdateBy(data.getCreateBy());
                if (!tbPurchaseApplyService.updateById(tbPurchaseApply)) {
                    log.error("修改采购申请提交状态失败");
                    throw new Exception("修改采购申请提交状态失败");
                }
            }
        }
        //修改采购订单的提交状态
//        this.updatePurchaseOrderSubmitStatus(data);
        return true;
    }

    //审批意见及附件
    public Boolean execProcessOpinion(Map<String, Object> param) throws Exception {
        // 审批意见
        SmsApprovalQuery data = StringUtils.toJavaBean(param, SmsApprovalQuery.class);
        if (StringUtils.isNotBlank(data.getOpinionText()) || (data.getTbPurchaseProcessOpinionFile() != null && data.getTbPurchaseProcessOpinionFile().size() != 0)) {
            Date currentDate = (Date) param.get("currentDate");
            TbPurchaseProcessOpinion tbPurchaseProcessOpinion = new TbPurchaseProcessOpinion();

            Object hiTaskId = param.get("hiTaskId");
            tbPurchaseProcessOpinion.setOpinionText(data.getOpinionText());
            tbPurchaseProcessOpinion.setNodeId(data.getNodeId());
            tbPurchaseProcessOpinion.setHiTaskId(String.valueOf(hiTaskId));
            tbPurchaseProcessOpinion.setDataId(data.getDataId());
            tbPurchaseProcessOpinion.setCreateDate(currentDate);
            tbPurchaseProcessOpinion.setUpdateDate(currentDate);
            tbPurchaseProcessOpinion.setCreateBy(data.getCreateBy());
            tbPurchaseProcessOpinion.setUpdateBy(data.getCreateBy());
            boolean save = tbPurchaseProcessOpinionService.save(tbPurchaseProcessOpinion);
            if (!save) {
                log.error("意见数据失败");
                throw new Exception("保存意见数据失败");
            }

            //意见附件 先删除后增加
            List<TbPurchaseProcessOpinionFile> tbPurchaseProcessOpinionFileList = data.getTbPurchaseProcessOpinionFile();
            if (StringUtils.isNotBlank(tbPurchaseProcessOpinionFileList)) {
                for (TbPurchaseProcessOpinionFile opinionFile : tbPurchaseProcessOpinionFileList
                ) {
                    TbPurchaseProcessOpinionFile tbPurchaseProcessOpinionFile = StringUtils.toJavaBean(opinionFile, TbPurchaseProcessOpinionFile.class);
                    tbPurchaseProcessOpinionFile.setOpinionId(tbPurchaseProcessOpinion.getId());
                    tbPurchaseProcessOpinionFile.setCreateBy(data.getCreateBy());
                    tbPurchaseProcessOpinionFile.setUpdateBy(data.getCreateBy());
                    tbPurchaseProcessOpinionFile.setCreateDate(currentDate);
                    tbPurchaseProcessOpinionFile.setUpdateDate(currentDate);
                    if (!tbPurchaseProcessOpinionFileService.save(tbPurchaseProcessOpinionFile)) {
                        log.error("保存意见附件数据失败");
                        throw new Exception("保存意见附件数据失败");
                    }
                }
            }
        }
        return true;
    }

    //修改采购订单的提交状态
    public Boolean updatePurchaseOrderSubmitStatus(SmsApprovalQuery data, String nodeName) throws Exception {
        // 修改采购订单提交状态 1 保存 2 提交
        TbPurchaseOrderSubtask tbPurchaseOrder = new TbPurchaseOrderSubtask();
        tbPurchaseOrder.setId(data.getDataId());
//        tbPurchaseOrder.setUpdateDate(new Date());
        tbPurchaseOrder.setUpdateBy(data.getCreateBy());
        tbPurchaseOrder.setSubmitStatus(data.getSubmitStatus());
        tbPurchaseOrder.setNodeName(nodeName);
        if (!tbPurchaseOrderSubtaskService.updateById(tbPurchaseOrder)) {
            log.error("修改采购订单任务子任务提交状态失败");
            throw new Exception("修改采购订单任务子任务提交状态失败");
        }
        return true;
    }

    //修改采购订单任务子任务的提交状态
    public Boolean updatePurchaseOrderSubtaskSubmitStatus(SmsApprovalQuery data, String nodeName) throws Exception {
        // 修改采购订单提交状态 1 保存 2 提交
        TbPurchaseOrderSubtask tbPurchaseOrderSubtask = new TbPurchaseOrderSubtask();
        tbPurchaseOrderSubtask.setId(data.getDataId());
        tbPurchaseOrderSubtask.setUpdateDate(new Date());
        tbPurchaseOrderSubtask.setUpdateBy(data.getCreateBy());
        tbPurchaseOrderSubtask.setSubmitStatus(data.getSubmitStatus());
        tbPurchaseOrderSubtask.setNodeName(nodeName);
        if (!tbPurchaseOrderSubtaskService.updateById(tbPurchaseOrderSubtask)) {
            log.error("修改采购订单任务子任务提交状态失败");
            throw new Exception("修改采购订单任务子任务提交状态失败");
        }
        return true;
    }

    /**
     * 处理审核
     *
     * @author 苏小林
     * @date 2020/3/17 14:05
     * @param: data
     * @return: boolean
     */
    public String handleAudit(Map<String, Object> data) throws Exception {
        //        boolean flag = true;
        String nodeName = "";
        // 数据id
        String dataId = StringUtils.getStringValue(data, "dataId");
        // 下一个节点审核用户id
        Object userId = data.get("userId");
        // 下一个节点审核用户角色
        Object roleIds = data.get("roleIds");
        // 下一个节点审核用户部门
        Object deptIds = data.get("deptIds");
        // 登录用户id
        String createBy = StringUtils.getStringValue(data, "createBy");
        // 节点id
        String nodeId = StringUtils.getStringValue(data, "nodeId");
        // 流程任务id
        Object processTaskId = data.get("processTaskId");
        Object type = data.get("processType");
        if (Objects.isNull(type)) {
            type = 1;
        }
        // 流程申请用户id
        String proposerId = StringUtils.getStringValue(data, "proposerId");
        // 状态
        Integer status = StringUtils.getIntegerValue(data, "status");
        //日期
        Date currentDate = new Date();

        Date date = new Date(System.currentTimeMillis() - 1000);
        // 中deal_with字段 0 通过 1 退回 2 重要
        try {
            // 查询下一节点
            Map<String, Object> map = getNextNode(nodeId, status, String.valueOf(type));
            Object nextNodeId = map.get("next_node_id");

            // 查询下一个节点的下一个节点名称
            String id = String.valueOf(map.get("nextId"));
            TbPurchaseProcessNode nextNode = tbPurchaseProcessNodeService.getById(id);

            List<TbPurchaseProcessTask> list = Lists.newArrayList();

            if (!Objects.isNull(nextNodeId) && StringUtils.isNotBlank(nextNodeId)) {
                if (!Objects.isNull(userId)) {
                    List<String> split = JSONArray.parseArray(String.valueOf(userId), String.class);
                    for (String s : split) {
                        // 添加下一个节点执行任务
                        TbPurchaseProcessTask tbPurchaseProcessTask =
                                new TbPurchaseProcessTask(
                                        s, "", "", dataId, String.valueOf(nextNodeId), createBy, proposerId, String.valueOf(type));
                        tbPurchaseProcessTask.setCreateDate(currentDate);
                        boolean saveTask = this.save(tbPurchaseProcessTask);
                        if (!saveTask) {
                            log.error("保存数据失败");
                            throw new Exception("保存数据失败");
                        }
                        list.add(tbPurchaseProcessTask);

                    }
                }

                // 角色
                if (!Objects.isNull(roleIds)) {
                    List<String> split1 = JSONArray.parseArray(String.valueOf(roleIds), String.class);
                    for (String s : split1) {
                        // 添加下一个节点执行任务
                        TbPurchaseProcessTask tbPurchaseProcessTask =
                                new TbPurchaseProcessTask(
                                        "", s, "", dataId, String.valueOf(nextNodeId), createBy, proposerId, String.valueOf(type));
                        tbPurchaseProcessTask.setCreateDate(currentDate);
                        boolean saveTask = this.save(tbPurchaseProcessTask);
                        if (!saveTask) {
                            log.error("保存数据失败");
                            throw new Exception("保存数据失败");
                        }
                        list.add(tbPurchaseProcessTask);

                    }
                }

                // 部门
                if (!Objects.isNull(deptIds)) {
                    List<String> splitDept = JSONArray.parseArray(String.valueOf(deptIds), String.class);
                    for (String s : splitDept) {
                        // 添加下一个节点执行任务
                        TbPurchaseProcessTask tbPurchaseProcessTask =
                                new TbPurchaseProcessTask(
                                        "", s, "", dataId, String.valueOf(nextNodeId), createBy, proposerId, String.valueOf(type));
                        tbPurchaseProcessTask.setCreateDate(currentDate);
                        boolean saveTask = this.save(tbPurchaseProcessTask);
                        if (!saveTask) {
                            log.error("保存数据失败");
                            throw new Exception("保存数据失败");
                        }
                        list.add(tbPurchaseProcessTask);

                    }
                }
            }

            // 添加下一个节点执行任务到历史任务
            for (TbPurchaseProcessTask tbPurchaseProcessTask : list) {
                if (tbPurchaseProcessTask != null) {
                    TbPurchaseProcessHiTask tbPurchaseProcessHiTask = new TbPurchaseProcessHiTask();
                    BeanUtils.copyProperties(tbPurchaseProcessTask, tbPurchaseProcessHiTask);
                    tbPurchaseProcessHiTask.setStatus(2);// 未审核
                    tbPurchaseProcessHiTask.setCreateDate(date);
                    tbPurchaseProcessHiTask.setUpdateDate(null);
                    tbPurchaseProcessHiTask.setUpdateBy("");
                    int insert = tbPurchaseProcessHiTaskMapper.insert(tbPurchaseProcessHiTask);
                    if (insert == 0) {
                        log.error("保存数据失败");
                        throw new Exception("保存数据失败");
                    }
                }
            }

            // 修改目前执行的任务
            updateRunTask(data, createBy, status, processTaskId, date);

            data.put("currentDate", currentDate);
            // 审批意见及附件
            this.execProcessOpinion(data);
            nodeName = nextNode.getNodeName();
        } catch (Exception e) {
            log.error("添加流程失败", e);
            throw new Exception(e);
        }
        return nodeName;
    }


    //一对多个流程
    public String handleZJAudit(Map<String, Object> data) throws Exception {
        String nodeName = "";
        // 数据id
        String dataId = String.valueOf(data.get("dataId"));
        // 下一个节点审核用户id
        Map<Integer, String> userId = (Map<Integer, String>) data.get("userId");
        // 下一个节点审核用户角色
        Map<Integer, String> roleIds = (Map<Integer, String>) data.get("roleIds");
        // 下一个节点审核用户部门
        Map<Integer, String> deptIds = (Map<Integer, String>) data.get("deptIds");
        // 登录用户id
        String createBy = String.valueOf(data.get("createBy"));
        // 节点id
        String nodeId = String.valueOf(data.get("nodeId"));
        // 状态
        Integer status = StringUtils.toInteger(data.get("status"));
        // 流程任务id
        Object processTaskId = data.get("processTaskId");
        Integer identification = (Integer) data.get("identification");
        Object type = data.get("processType");
        if (Objects.isNull(type)) {
            type = 1;
        }

        // 流程申请用户id
        String proposerId = String.valueOf(data.get("proposerId"));
        //日期
        Date currentDate = new Date();
        // 中deal_with字段 0 通过 1 退回 2 重要
        try {
            // 查询下一节点
            List<Map<String, Object>> maps = null;
            maps = getZJNextNodeId(nodeId, String.valueOf(type));
            if (StringUtils.isNotBlank(identification)) {
                if (identification == 0) {
                    maps = tbPurchaseProcessNodeService.getContractFirstNode(type);
                }
            }

            for (Map<String, Object> map : maps) {
                Object nextNodeId = map.get("next_node_id");
                Object dealWith = map.get("deal_with");
                //判断下一个流程是否存在
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("node_id", nextNodeId);
                queryWrapper.eq("data_id", dataId);
                List list = super.list(queryWrapper);
                if (list.size() == 0) {
                    TbPurchaseProcessTask tbPurchaseProcessTask = null;
                    if (!Objects.isNull(nextNodeId) && StringUtils.isNotBlank(nextNodeId)) {
                        if (!Objects.isNull(userId) && StringUtils.isNotBlank(userId.get(dealWith)) && userId.containsKey(dealWith)) {
                            List<String> split = JSONArray.parseArray(String.valueOf(userId.get(dealWith)), String.class);
                            for (String s : split) {
                                // 添加下一个节点执行任务
                                tbPurchaseProcessTask =
                                        new TbPurchaseProcessTask(
                                                s, "", "", dataId, String.valueOf(nextNodeId), createBy, proposerId, String.valueOf(type));
                                tbPurchaseProcessTask.setCreateDate(currentDate);
                                boolean saveTask = this.save(tbPurchaseProcessTask);
                                if (!saveTask) {
                                    log.error("保存数据失败");
                                    throw new Exception("保存数据失败");
                                }

                            }
                        }

                        // 角色
                        if (!Objects.isNull(roleIds) && StringUtils.isNotBlank(roleIds.get(dealWith)) && roleIds.containsKey(dealWith)) {
                            List<String> split1 = JSONArray.parseArray(String.valueOf(roleIds.get(dealWith)), String.class);
                            for (String s : split1) {
                                // 添加正在执行任务
                                tbPurchaseProcessTask =
                                        new TbPurchaseProcessTask(
                                                "", s, "", dataId, String.valueOf(nextNodeId), createBy, proposerId, String.valueOf(type));
                                tbPurchaseProcessTask.setCreateDate(currentDate);
                                boolean saveTask = this.save(tbPurchaseProcessTask);
                                if (!saveTask) {
                                    log.error("保存数据失败");
                                    throw new Exception("保存数据失败");
                                }

                            }
                        }

                        // 部门
                        if (!Objects.isNull(deptIds) && StringUtils.isNotBlank(deptIds.get(dealWith)) && deptIds.containsKey(dealWith)) {
                            List<String> splitDept = JSONArray.parseArray(String.valueOf(deptIds.get(dealWith)), String.class);
                            for (String s : splitDept) {
                                // 添加正在执行任务
                                tbPurchaseProcessTask =
                                        new TbPurchaseProcessTask(
                                                "", s, "", dataId, String.valueOf(nextNodeId), createBy, proposerId, String.valueOf(type));
                                tbPurchaseProcessTask.setCreateDate(currentDate);
                                boolean saveTask = this.save(tbPurchaseProcessTask);
                                if (!saveTask) {
                                    log.error("保存数据失败");
                                    throw new Exception("保存数据失败");
                                }

                            }
                        }
                    }

                    // 添加正在执行任务到历史任务
                    if (tbPurchaseProcessTask != null) {
                        TbPurchaseProcessHiTask tbPurchaseProcessHiTask = new TbPurchaseProcessHiTask();
                        BeanUtils.copyProperties(tbPurchaseProcessTask, tbPurchaseProcessHiTask);
                        tbPurchaseProcessHiTask.setStatus(2);// 未审核
                        tbPurchaseProcessHiTask.setUpdateDate(null);
                        tbPurchaseProcessHiTask.setUpdateBy("");
                        int insert = tbPurchaseProcessHiTaskMapper.insert(tbPurchaseProcessHiTask);
                        if (insert == 0) {
                            log.error("保存数据失败");
                            throw new Exception("保存数据失败");
                        }
                    }
                    nodeName = String.valueOf(map.get("node_name"));

                }
            }
            if (StringUtils.isBlank(identification)) {
                updateRunTask(data, createBy, status, processTaskId, currentDate);
            }

            data.put("currentDate", currentDate);
            // 审批意见及附件
            this.execProcessOpinion(data);
        } catch (Exception e) {
            log.error("添加流程失败", e);
            throw new Exception(e);
        }
        return nodeName;
    }

    private void updateRunTask(Map<String, Object> data, String createBy, Integer status, Object processTaskId, Date currentDate) throws Exception {
        // 修改目前执行的任务
        if (StringUtils.isNotBlank(processTaskId)) {
            String s = String.valueOf(processTaskId);
            // 删除正在执行任务
            int row1 = dao.deleteTaskById(s);
            if (row1 == 0) {
                log.error("保存数据失败");
                throw new Exception("保存数据失败");
            }

            TbPurchaseProcessHiTask processHiTask = new TbPurchaseProcessHiTask();
            processHiTask.setId(s);
            processHiTask.setUserId(createBy);
            processHiTask.setUpdateBy(createBy);
            processHiTask.setUpdateDate(currentDate);
            processHiTask.setStatus(0);
            if (status == 1) {
                processHiTask.setStatus(1);
            }
            boolean update = tbPurchaseProcessHiTaskService.updateById(processHiTask);
            if (!update) {
                log.error("保存数据失败");
                throw new Exception("保存数据失败");
            }
            data.put("hiTaskId", s);

        }
    }

    //关闭订单-合同
    public String closeContractOrderHandleAudit(Map<String, Object> data) throws Exception {
        String nodeName = "";
        // 登录用户id
        String createBy = String.valueOf(data.get("createBy"));
        // 节点id
        String nodeId = String.valueOf(data.get("nodeId"));
        String processTaskId = String.valueOf(data.get("processTaskId"));
        Object type = data.get("processType");
        if (Objects.isNull(type)) {
            type = 1;
        }
        // 状态
        Integer status = StringUtils.toInteger(data.get("status")); // 对应节点表
        //日期
        Date currentDate = new Date();
        // 中deal_with字段 0 通过 1 退回 2 重要
        try {
            // 查询下一节点
            Map<String, Object> map = getNextNode(nodeId, status, String.valueOf(type));
            // 修改目前执行的任务
            updateRunTask(data, createBy, status, processTaskId, currentDate);
            if (StringUtils.isNotBlank(data.get("purchaseOrderId"))) {
                int row2 = dao.deleteTaskByDataId(String.valueOf(data.get("purchaseOrderId")));
                if (row2 == 0) {
                    log.error("删除订单数据失败");
                    throw new Exception("删除订单数据失败");
                }
            }
            data.put("currentDate", currentDate);

            // 审批意见及附件
            this.execProcessOpinion(data);
            nodeName = String.valueOf(map.get("node_name"));
        } catch (Exception e) {
            log.error("添加流程失败", e);
            throw new Exception(e);
        }
        return nodeName;
    }

    //删除正在执行的流程和保存历史记录
    public boolean deleteHandleAuditAndSaveHi(Map<String, Object> data) throws Exception {
        // 登录用户id
        String createBy = String.valueOf(data.get("createBy"));
        // 节点id
        String processTaskId = String.valueOf(data.get("processTaskId"));
        Object type = data.get("processType");
        if (Objects.isNull(type)) {
            type = 1;
        }
        // 状态
        Integer status = StringUtils.toInteger(data.get("status")); // 对应节点表
        //日期
        Date currentDate = new Date();
        // 中deal_with字段 0 通过 1 退回 2 重要
        try {
            // 修改目前执行的任务
            updateRunTask(data, createBy, status, processTaskId, currentDate);
            data.put("currentDate", currentDate);
            // 审批意见及附件
            this.execProcessOpinion(data);
        } catch (Exception e) {
            log.error("添加流程失败", e);
            throw new Exception(e);
        }
        return true;
    }


    public String handleAuditAllPass(Map<String, Object> data) throws Exception {
        String nodeName = "";
        // 数据id
        String dataId = String.valueOf(data.get("dataId"));
        // 下一个节点审核用户id
        Object userId = data.get("userId");
        // 下一个节点审核用户角色
        Object roleIds = data.get("roleIds");
        // 下一个节点审核用户部门
        Object deptIds = data.get("deptIds");
        // 登录用户id
        String createBy = String.valueOf(data.get("createBy"));
        // 节点id
        String nodeId = String.valueOf(data.get("nodeId"));
        // 审核意见
        // 流程申请用户id
        String proposerId = String.valueOf(data.get("proposerId"));
        // 状态
        Integer status = StringUtils.toInteger(data.get("status")); // 对应节点表
        //日期
        Date currentDate = new Date();
        // 中deal_with字段 0 通过 1 退回 2 重要
        try {
            //获取当前用户得角色id和部门id
            List<String> departIdsByUserId = tbGlobalUserMapper.getDepartIdsByUserId(StringUtils.toLong(createBy));
            //角色
            List<String> roleListByUserId = tbGlobalUserService.getRoleListByUserId(StringUtils.toLong(createBy));
            //查询除了自己是否都审核完了
            List<String> taskByParam = dao.getTaskByParam(dataId, nodeId, departIdsByUserId, roleListByUserId, createBy);
            if (taskByParam.size() == 0) {
                // 查询下一节点
                Map<String, Object> map = getNextNode(nodeId, status, "2");
                Object nextNodeId = map.get("next_node_id");
                // 查询下一个节点的下一个节点名称
                String id = String.valueOf(map.get("nextId"));
                TbPurchaseProcessNode nextNode = tbPurchaseProcessNodeService.getById(id);
                if (!Objects.isNull(nextNodeId) && StringUtils.isNotBlank(nextNodeId)) {
                    if (!Objects.isNull(userId)) {
                        List<String> split = JSONArray.parseArray(String.valueOf(userId), String.class);
                        for (String s : split) {
                            // 添加下一个节点执行任务
                            TbPurchaseProcessTask tbPurchaseProcessTask =
                                    new TbPurchaseProcessTask(
                                            s, "", "", dataId, String.valueOf(nextNodeId), createBy, proposerId, "2");
                            tbPurchaseProcessTask.setCreateDate(currentDate);
                            boolean saveTask = this.save(tbPurchaseProcessTask);
                            if (!saveTask) {
                                log.error("保存数据失败");
                                throw new Exception("保存数据失败");
                            }

                        }
                    }

                    // 角色
                    if (!Objects.isNull(roleIds)) {
                        List<String> split1 = JSONArray.parseArray(String.valueOf(roleIds), String.class);
                        for (String s : split1) {
                            // 添加正在执行任务
                            TbPurchaseProcessTask tbPurchaseProcessTask =
                                    new TbPurchaseProcessTask(
                                            "", s, "", dataId, String.valueOf(nextNodeId), createBy, proposerId, "2");
                            tbPurchaseProcessTask.setCreateDate(currentDate);
                            boolean saveTask = this.save(tbPurchaseProcessTask);
                            if (!saveTask) {
                                log.error("保存数据失败");
                                throw new Exception("保存数据失败");
                            }

                        }
                    }

                    //部门
                    if (!Objects.isNull(deptIds)) {
                        List<String> splitDept = JSONArray.parseArray(String.valueOf(deptIds), String.class);
                        for (String s : splitDept) {
                            // 添加正在执行任务
                            TbPurchaseProcessTask tbPurchaseProcessTask =
                                    new TbPurchaseProcessTask(
                                            "", s, "", dataId, String.valueOf(nextNodeId), createBy, proposerId, "2");
                            tbPurchaseProcessTask.setCreateDate(currentDate);
                            boolean saveTask = this.save(tbPurchaseProcessTask);
                            if (!saveTask) {
                                log.error("保存数据失败");
                                throw new Exception("保存数据失败");
                            }
                        }
                    }
                }
                nodeName = nextNode.getNodeName();
            }

            //获取历史表中create_date流程得开始时间 和流程得create_by创建人
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.select("DISTINCT create_by,create_date");
            queryWrapper.eq("node_id", nodeId);
            queryWrapper.eq("data_id", dataId);
            TbPurchaseProcessTask tbPurchaseProcessTask = super.getOne(queryWrapper);
            // 修改目前执行的任务
            TbPurchaseProcessHiTask tbPurchaseProcessHiTask = new TbPurchaseProcessHiTask();
            tbPurchaseProcessHiTask.setUserId(createBy);
            tbPurchaseProcessHiTask.setDataId(dataId);
            tbPurchaseProcessHiTask.setNodeId(nodeId);
            tbPurchaseProcessHiTask.setUpdateBy(createBy);
            tbPurchaseProcessHiTask.setUpdateDate(currentDate);
            tbPurchaseProcessHiTask.setCreateDate(tbPurchaseProcessTask.getCreateDate());
            tbPurchaseProcessHiTask.setCreateBy(tbPurchaseProcessTask.getCreateBy());
            tbPurchaseProcessHiTask.setProposerId(proposerId);
            tbPurchaseProcessHiTask.setStatus(0); // 审核通过
            if (status == 1) {
                tbPurchaseProcessHiTask.setStatus(1); // 审核退回
            }
            if (!tbPurchaseProcessHiTaskService.save(tbPurchaseProcessHiTask)) {
                log.error("修改数据失败");
                throw new Exception("修改数据失败");
            }

            //删除正在执行得流程
            int row1 = dao.deleteTaskByParam(dataId, nodeId, departIdsByUserId, roleListByUserId, createBy);
            if (row1 != 1) {
                log.error("删除数据失败row1={}当row1=0时正在执行得流程节点错误当row1>1有可能用户id,部门id，角色id有相等", row1);
                throw new Exception("删除数据失败当row1=0时正在执行得流程节点错误当row1>1有可能用户id,部门id，角色id有相等");
            }
            // 审批意见及附件
            data.put("currentDate", currentDate);
            this.execProcessOpinion(data);

        } catch (Exception e) {
            log.error("添加流程失败", e);
            throw new Exception(e);
        }
        return nodeName;
    }


    /**
     * 获取下一个节点
     *
     * @author 苏小林
     * @date 2020/3/19 13:47
     * @param: nodeId
     * @param: status
     * @return: java.util.Map<java.lang.String                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               ,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               java.lang.Object>
     */
    private Map<String, Object> getNextNode(String nodeId, Integer status, String type) {
        //        QueryWrapper queryWrapper = new QueryWrapper();
        //        queryWrapper.select("id","next_node_id","node_name","audit_role","audit_user");
        //        queryWrapper.eq("node_id",nodeId);
        //        queryWrapper.eq("deal_with",status);
        //        return tbPurchaseProcessNodeService.getMap(queryWrapper);
        return tbPurchaseProcessNodeService.getNextNodeId(nodeId, status, type);
    }

    //得到核检的下一个流程
    private List<Map<String, Object>> getZJNextNodeId(String nodeId, String type) {
        return tbPurchaseProcessNodeService.getZJNextNodeId(nodeId, type);
    }


    //  保存修改订单
    public boolean saveUpdatePurchaseOrder(PayContractQuerySms data) throws Exception {
        // 保存到付费申请表
        TbPurchaseOrder tbPurchaseOrder = StringUtils.toJavaBean(data, TbPurchaseOrder.class);
        tbPurchaseOrder.setId(data.getDataId());
        tbPurchaseOrder.setUpdateBy(data.getCreateBy());
//        tbPurchaseOrder.setPaymentWay(data.getPaymentWay());
//        tbPurchaseOrder.setAdvanceProportion(data.getAdvanceProportion());
//        tbPurchaseOrder.setSecondProportion(data.getSecondProportion());
//        tbPurchaseOrder.setFinalProportion(data.getFinalProportion());
        if (StringUtils.isBlank(tbPurchaseOrder.getId())) {
            tbPurchaseOrder.setCreateBy(data.getCreateBy());
        }
        if (!tbPurchaseOrderService.save(tbPurchaseOrder)) {
            log.error("保存修改订单表失败");
            throw new Exception("保存修改订单失败");
        }
        return true;
    }

    //  保存申请付款
    public boolean savePayApproval(UploadContractFileQuerySms data) throws Exception {
        // 保存到付费申请表
        TbPurchaseSubtaskPaymentApply tbPurchaseOrderPaymentApply = StringUtils.toJavaBean(data, TbPurchaseSubtaskPaymentApply.class);
        tbPurchaseOrderPaymentApply.setId(data.getPayMentId());
        tbPurchaseOrderPaymentApply.setUpdateBy(data.getCreateBy());
        tbPurchaseOrderPaymentApply.setDataId(data.getDataId());
        tbPurchaseOrderPaymentApply.setAuditStatus(2);
        if (StringUtils.isBlank(tbPurchaseOrderPaymentApply.getId())) {
            tbPurchaseOrderPaymentApply.setCreateBy(data.getCreateBy());
        }
        if (!tbPurchaseSubtaskPaymentApplyService.save(tbPurchaseOrderPaymentApply)) {
            log.error("保存到付费申请表失败");
            throw new Exception("保存到付费申请表失败");
        }
        return true;
    }

    //  保存合同
    public boolean saveContractApproval(PayContractQuerySms data) throws Exception {
        // 保存合同
        //先删后加
        //删除合同相关得文件
        int i = tbPurchaseOrderFileService.removeOrderFile(data.getPurchaseTaskId(), data.getDataId(), data.getNodeId(), data.getType());
        Date date = new Date();
        List<TbPurchaseSubtaskOtherFile> tbPurchaseOrderFileList = data.getTbPurchaseOrderFileList();
        if (tbPurchaseOrderFileList.size() != 0) {
            for (TbPurchaseSubtaskOtherFile tbPurchaseOrderFile : tbPurchaseOrderFileList) {
                tbPurchaseOrderFile.setId(IdGen.uuid());
                tbPurchaseOrderFile.setDataId(data.getDataId());
                tbPurchaseOrderFile.setNodeId(data.getNodeId());
                tbPurchaseOrderFile.setType(data.getType());
                tbPurchaseOrderFile.setUpdateBy(data.getCreateBy());
                tbPurchaseOrderFile.setCreateBy(data.getCreateBy());
                tbPurchaseOrderFile.setCreateDate(date);
                tbPurchaseOrderFile.setUpdateDate(date);
            }
            if (!tbPurchaseSubtaskOtherFileService.saveOrUpdateBatch(tbPurchaseOrderFileList)) {
                log.error("保存合同失败");
                throw new Exception("保存合同失败");
            }
        }
        return true;
    }

    //    总经理审批供应链部门低值/固值付款申请
    public boolean managerLSValuePayApproval(ManagerLSValuePaySmsApprovalQuery data) throws Exception {
        //流程
        this.execProcessOrderSubtask(data);
        //修改支付申请表审核状态 0审核通过 1审核退回 2未审核
        if (data.getStatus() == 0) {
            data.setAuditStatus("0");
        } else if (data.getStatus() == 1) {
            data.setAuditStatus("1");
        }
        Map<String, Object> mapParam = StringUtils.toJavaBean(data, Map.class);
        this.updateOrderPaymentAuditStatus(mapParam);
        return true;
    }

    // 上传付款凭证
    public boolean uploadBillOfCredit(FinanceLSValuePaySmsApprovalQuery data) throws Exception {
        // 保存到采购订单-采购订单其他文件付款
        data.setType(4);
        this.saveOrderOtherFile(data);
        // 保存支付记录
        if (data.getSubmitStatus() == 2) {
            Map<String, Object> mapParam = StringUtils.toJavaBean(data, Map.class);
            this.saveOrderPaymentRecord(mapParam);
        }

        // 查询财务主管
        Long roleId = tbGlobalUserMapper.getRoleIdByRoleKeyName(financialManager);
        String processTaskId = data.getProcessTaskId();
        TbPurchaseProcessTask tbPurchaseProcessTask = new TbPurchaseProcessTask();
        tbPurchaseProcessTask.setId(processTaskId);
        tbPurchaseProcessTask.setRoleId(String.valueOf(roleId));
        int i = dao.updateById(tbPurchaseProcessTask);
        if (i == 0) {
            log.error("修改审核角色失败");
            throw new Exception("修改审核角色失败");
        }
        return true;
    }

    //  "财务付款低值/固值
    public boolean financeLSValuePayApproval(FinanceLSValuePaySmsApprovalQuery data) throws Exception {
        //流程
        this.execProcessOrderSubtask(data);
        return true;
    }

    // 公共流程采购订单
    public boolean execZJProcessOrder(PurchaseOrderQuerySms data) throws Exception {
        //流程
        String s = null;
        if (data.getSubmitStatus() == 2) {
            data.setProcessType("2");
            Map<String, Object> mapParam = JSON.parseObject(JSON.toJSONString(data), Map.class);
            s = this.handleZJAudit(mapParam);
        }
        //修改采购订单的提交状态
        this.updatePurchaseOrderSubtaskSubmitStatus(data, s);
        return true;
    }

    //  供应链部核对采购清单/上传报检清单
    public boolean checkPurchaseListApproval(CheckPurchaseListSmsApprovalQuery data) throws Exception {
        this.execProcessOrderSubtask(data);
        data.setType(0);
        return this.saveOrderOtherFile(data);
    }


    //  质检记录
    public boolean checkPurchaseRecordApproval(CheckPurchaseRecordSmsApprovalQuery data) throws Exception {
        //获取质检最大批次
        String maxBatch = tbPurchaseSubtaskQualityRecordService.getMaxBatch(data.getDataId());
        if (StringUtils.isBlank(maxBatch)) {
            maxBatch = "0";
        }
        int batch = StringUtils.toInteger(maxBatch).intValue();
        batch++;
        data.setQualityRecordBatch(batch);
        // 保存采购订单任务子任务-质检记录和指派人
        if (data.getSubmitStatus() == 2) {
            this.saveOrderQualityRecord(data);
            //流程
            this.execZJProcessOrder(data);
            //修改订单任务子任务表bad_records 物料不良记录 0无 1有
            TbPurchaseOrderSubtask tbPurchaseOrderSubtask = new TbPurchaseOrderSubtask();
            tbPurchaseOrderSubtask.setId(data.getDataId());
            if ("1".equals(data.getBadRecords())) {
                tbPurchaseOrderSubtask.setBadRecords(data.getBadRecords());
            }
            tbPurchaseOrderSubtask.setTotalInStorageNumber(data.getTotalInstorageNumber());
            tbPurchaseOrderSubtask.setTotalBackNumber(data.getTotalBackNumber());
            tbPurchaseOrderSubtask.setTotalNumber(data.getTotalNumber() - data.getCurrentBackNumber());
            if (!tbPurchaseOrderSubtaskService.updateById(tbPurchaseOrderSubtask)) {
                log.error("期款申请修改订单任务子任务表失败");
                throw new Exception("期款申请任务子任务修改订单表失败");
            }
        }

        //指派人由map格式转String
        if (StringUtils.isNotBlank(data.getUserId())) {
            Map<Integer, Object> userId = (Map<Integer, Object>) data.getUserId();
            data.setUserId(userId.get(6));
        }

        if (StringUtils.isNotBlank(data.getRoleIds())) {
            Map<Integer, Object> roleIds = (Map<Integer, Object>) data.getRoleIds();
            data.setRoleIds(roleIds.get(0));
        }
        return true;
    }

    //    仓管部入库
    public Message storageApproval(StorageSmsApprovalQuery data) throws Exception {
        //获取入库最大批次
        String maxBatch = tbPurchaseSubtaskStorageRecordService.getMaxBatch(data.getDataId());
        if (StringUtils.isBlank(maxBatch)) {
            maxBatch = "0";
        }
        int batch = StringUtils.toInteger(maxBatch).intValue();
        batch++;
        data.setStorageRecordBatch(batch);
        //  保存采购订单任务子任务-入库记录
        this.saveOrderStorageRecord(data);
        //修改质检记录表中入库状态(0 未完成 1 已完成)
        if (!tbPurchaseSubtaskQualityRecordService.updateStorageStatus(1, data.getRecordBatch(), data.getDataId())) {
            log.error("修改质检记录表中入库状态失败");
            throw new Exception("修改质检记录表中入库状态失败");
        }
        //保存采购订单任务子任务-入库单
        saveSubtaskStorageRecordFile(data);
        //获取总数量
        TbPurchaseOrderSubtask byId = tbPurchaseOrderSubtaskService.getById(data.getDataId());
        if (byId.getTotalNumber() == data.getTotalInstorageNumber()) {
            Integer paymentWay = byId.getPaymentWay();
            if (paymentWay != null && paymentWay == 1) {
                data.setStatus(3);
                //当前有没有正在执行的流程
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("data_id", data.getDataId());
                queryWrapper.notIn("node_id", data.getNodeId());
                List list = dao.selectList(queryWrapper);
                if (list.size() != 0) {
                    //删除正在执行的流程和保存历史记录
                    data.setProcessType("2");
                    Map mapParam = StringUtils.toJavaBean(data, Map.class);
                    if (this.deleteHandleAuditAndSaveHi(mapParam)) {
                        return Message.success("成功");
                    }
                }
            }

            if (StringUtils.toInteger(data.getStatus()) == 0 && data.getSubmitStatus() == 2) {//入库到二期款申请
                //采购文件编写员
                data.setUserId(Arrays.asList(data.getProposerId().split(",")));
            } else if (StringUtils.toInteger(data.getStatus()) != 0 && StringUtils.toInteger(data.getStatus()) != 3) {
                log.error("仓管部入库status只能为0，3");
                throw new Exception("仓管部入库status只能为0，3");
            }
            //流程
            this.execProcessOrderSubtask(data);
            Thread.sleep(1000);
            if (StringUtils.toInteger(data.getStatus()) == 3 && data.getSubmitStatus() == 2) { // 保存订单结束节点到历史表
                TbPurchaseProcessHiTask tbPurchaseProcessHiTask = new TbPurchaseProcessHiTask("", data.getDataId(), "3812CE6C40334DCDAE35DC5E5621B887", 0, data.getProposerId(), data.getCreateBy(), "2");
                this.saveProcessHiTask(tbPurchaseProcessHiTask);
            }
        } else if (byId.getTotalNumber() > data.getTotalInstorageNumber()) {
            //删除正在执行的流程和保存历史记录
            data.setProcessType("2");
            Map mapParam = StringUtils.toJavaBean(data, Map.class);
            this.deleteHandleAuditAndSaveHi(mapParam);
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
            return Message.error(1, "入库数大于申请入库数");
        }
        return Message.success("成功");
    }


    public boolean delByDataId(String id) {
        Integer result = dao.delByDataId(id);
        return null != result && result >= 0;
    }

    public boolean saveLVPayApproval(TbPurchaseOrderSubtask data) throws Exception {
        // 保存到付费申请表
        TbPurchaseSubtaskPaymentApply tbPurchaseOrderPaymentApply = new TbPurchaseSubtaskPaymentApply();
        tbPurchaseOrderPaymentApply.setId(data.getPayMentId());
        tbPurchaseOrderPaymentApply.setUpdateBy(data.getCreateBy());
        tbPurchaseOrderPaymentApply.setDataId(data.getId());
        tbPurchaseOrderPaymentApply.setPaymentMoney(data.getTotalMoney());
        tbPurchaseOrderPaymentApply.setAuditStatus(2);
        if (StringUtils.isBlank(tbPurchaseOrderPaymentApply.getId())) {
            tbPurchaseOrderPaymentApply.setCreateBy(data.getCreateBy());
        }
        if (!tbPurchaseSubtaskPaymentApplyService.save(tbPurchaseOrderPaymentApply)) {
            log.error("保存到付费申请表失败");
            throw new Exception("保存到付费申请表失败");
        }
        return true;
    }

//    public void createPurchaseOrder(TbPurchaseOrder tbPurchaseOrder) throws Exception {
//        String createBy = tbPurchaseOrder.getCreateBy();// 当前登录用户
//        List<String> roleNames = tbGlobalUserService.getRoleNamesByUserId(StringUtils.toLong(createBy));
//        String category = tbPurchaseOrder.getCategory();
//
//        if (!roleNames.contains(roleNameThree)) {//如果角色中不包含采购经理
//            tbPurchaseOrder.setNodeId("EF6495D140AA4A3A809883A3EA298844");
//        }else{
//            tbPurchaseOrder.setNodeId("253CBECAAB5342CBA4EFC3FE56B1F34C");
//            if (!"3".equals(category)) {
////                tbPurchaseOrder.setStatus(5);
//            }
//
//        }
//        savePurchaseOrder(tbPurchaseOrder);
//
//    }


    /**
     * 保存采购订单
     * @author 苏小林
     * @date 2020/8/24 11:20
     * @param: tbPurchaseOrderListQuery
     */
    public void savePurchaseOrderList(TbPurchaseOrderListQuery tbPurchaseOrderListQuery) throws Exception {
        this.deltPurchaseOrder(tbPurchaseOrderListQuery.getPurchaseTaskId());
        List<TbPurchaseOrder> purchaseOrderList = tbPurchaseOrderListQuery.getPurchaseOrderList();
        for (TbPurchaseOrder tbPurchaseOrder : purchaseOrderList) {
            tbPurchaseOrder.setPurchaseTaskId(tbPurchaseOrderListQuery.getPurchaseTaskId());
            tbPurchaseOrder.setDealWithStatus("未处理");
            tbPurchaseOrder.setSubmitStatus(tbPurchaseOrderListQuery.getSubmitStatus());
            this.savePurchaseOrder(tbPurchaseOrder);
        }

        if (tbPurchaseOrderListQuery.getSubmitStatus() == 2) {// 提交
            this.startPurchaseOrderProcess(tbPurchaseOrderListQuery);
        }

        // 修改采购任务状态
        if (purchaseOrderList != null && purchaseOrderList.size() > 0) {
            String purchaseTaskId = tbPurchaseOrderListQuery.getPurchaseTaskId();
            TbPurchaseTask tbPurchaseTask = new TbPurchaseTask();
            tbPurchaseTask.setId(purchaseTaskId);
            tbPurchaseTask.setDealWithStatus("已处理");
            tbPurchaseTaskService.updateById(tbPurchaseTask);
        }


    }


    private void startPurchaseOrderProcess(TbPurchaseOrderListQuery tbPurchaseOrderListQuery) throws Exception {

        String nodeId = "a94361f2f8654c3aa8fe516f502ee4fc";// 准备采购订单
        String createBy = tbPurchaseOrderListQuery.getCreateBy();// 当前登录用户
        List<String> roleNames = tbGlobalUserMapper.getRoleKeyNamesByUserId(StringUtils.toLong(createBy));
        PurchaseOrderQuerySms approvalQuery = new PurchaseOrderQuerySms();
        approvalQuery.setNodeId(nodeId);

        if (!roleNames.contains(roleNameThree)) {//如果角色中不包含采购经理
            approvalQuery.setStatus(0); // 采购员
            //查询采购经理角色列表
            List<String> roleNameList = new ArrayList<>();
            roleNameList.add(roleNameThree);
            Set<String> roleListByRoleName = tbGlobalUserMapper.getRoleListByRoleKeyName(roleNameList);
            approvalQuery.setRoleIds(roleListByRoleName);
        } else {
            approvalQuery.setStatus(10);// 采购经理

            // 查询财务角色列表
            List<String> roleNameList = new ArrayList<>();
            roleNameList.add(financialManager);
            Set<String> roleListByRoleName = tbGlobalUserMapper.getRoleListByRoleKeyName(roleNameList);
            approvalQuery.setRoleIds(roleListByRoleName);
        }

        // 流程id为空
        if (StringUtils.isBlank(tbPurchaseOrderListQuery.getProcessTaskId())) {
            TbPurchaseProcessTask tbPurchaseProcessTask = dao.getByDataId(tbPurchaseOrderListQuery.getPurchaseTaskId());
            tbPurchaseOrderListQuery.setProcessTaskId(tbPurchaseProcessTask.getId());
        }

        approvalQuery.setPurchaseTaskId(tbPurchaseOrderListQuery.getPurchaseTaskId());
        approvalQuery.setDataId(tbPurchaseOrderListQuery.getPurchaseTaskId());
        approvalQuery.setCreateBy(tbPurchaseOrderListQuery.getCreateBy());
        approvalQuery.setSubmitStatus(tbPurchaseOrderListQuery.getSubmitStatus());
        approvalQuery.setProcessTaskId(tbPurchaseOrderListQuery.getProcessTaskId());
        approvalQuery.setProposerId(tbPurchaseOrderListQuery.getCreateBy());
        approvalQuery.setProcessType("1");
//        Map<String, Object> mapParam = JSON.parseObject(JSON.toJSONString(approvalQuery), Map.class);
//        this.handleAudit(mapParam);
        execProcess(approvalQuery);

        sendMessage(approvalQuery);
    }

    /**
     * 保存采购订单
     *
     * @author 苏小林
     * @date 2020/4/23 17:28
     * @param: tbPurchaseOrder
     */
    private void savePurchaseOrder(TbPurchaseOrder tbPurchaseOrder) throws Exception {
        try {
            // 保存采购清单
            List<TbPurchaseOrderGoods> purchaseOrderGoodsList = tbPurchaseOrder.getPurchaseOrderGoodsList();
            if (purchaseOrderGoodsList != null && purchaseOrderGoodsList.size() > 0) {
                if (StringUtils.isNotBlank(tbPurchaseOrder.getId())) {
                    this.deltPurchaseOrder(tbPurchaseOrder.getId());
                    tbPurchaseOrder.setId("");
                }

                String orderNewNum = tbPurchaseApplyService.getOrderNewNum(StringUtils.toInteger(tbPurchaseOrder.getDeptId()), tbPurchaseOrder.getCategory());
                tbPurchaseOrder.setOrderNumber(orderNewNum);
                boolean save = tbPurchaseOrderService.save(tbPurchaseOrder);
                if (!save) {
                    log.error("保存采购订单主表出错");
                    throw new Exception("保存采购订单主表出错");
                }


//            List<String> ids = purchaseOrderGoodsList.stream().map(TbPurchaseOrderGoods::getId).collect(Collectors.toList());
                if (!purchaseOrderGoodsList.isEmpty()) {
                    for (TbPurchaseOrderGoods tbPurchaseOrderGoods : purchaseOrderGoodsList) {
                        if (StringUtils.isBlank(tbPurchaseOrderGoods.getId())) {
                            tbPurchaseOrderGoods.setId(IdGen.uuid());
                        }
                        tbPurchaseOrderGoods.setCreateDate(new Date());
                        tbPurchaseOrderGoods.setPurchaseOrderId(tbPurchaseOrder.getId());// 采购订单id
                        tbPurchaseOrderGoods.setPurchaseTaskId(tbPurchaseOrder.getPurchaseTaskId());// 采购任务id
                        tbPurchaseOrderGoods.setCreateBy(tbPurchaseOrder.getCreateBy());
                        tbPurchaseOrderGoods.setUpdateBy(tbPurchaseOrder.getCreateBy());
                        tbPurchaseOrderGoods.setUpdateDate(new Date());
                    }

                    boolean b = tbPurchaseOrderGoodsService.saveBatch(purchaseOrderGoodsList);
                    if (!b) {
                        log.error("保存采购清单文件出错");
                        throw new Exception("保存采购清单文件出错");
                    }
                }

//            tbPurchaseTaskListMapper.updateSelect(ids);

                // 保存采购计划文件
                List<TbPurchaseOrderFile> purchasePlanFileList = tbPurchaseOrder.getPurchasePlanFile();
                if (!purchasePlanFileList.isEmpty()) {
                    for (TbPurchaseOrderFile purchasePlanFile : purchasePlanFileList) {
                        purchasePlanFile.setId(IdGen.uuid());
                        purchasePlanFile.setCreateDate(new Date());
                        purchasePlanFile.setNodeId(tbPurchaseOrder.getNodeId());
                        purchasePlanFile.setDataId(tbPurchaseOrder.getId());
//                    purchasePlanFile.setPurchaseApplyId(tbPurchaseOrder.getPurchaseApplyId());
                        purchasePlanFile.setCreateBy(tbPurchaseOrder.getCreateBy());
                        purchasePlanFile.setUpdateBy(tbPurchaseOrder.getCreateBy());
                        purchasePlanFile.setUpdateDate(new Date());
                    }

                    boolean b = tbPurchaseOrderFileService.saveBatch(purchasePlanFileList);
                    if (!b) {
                        log.error("保存采购计划文件出错");
                        throw new Exception("保存采购计划文件出错");
                    }
                }

                // 采购订单文件
                List<TbPurchaseOrderFile> purchaseOrderFileList = tbPurchaseOrder.getPurchaseOrderFile();
                if (!purchaseOrderFileList.isEmpty()) {
                    for (TbPurchaseOrderFile purchaseOrderFile : purchaseOrderFileList) {
                        purchaseOrderFile.setId(IdGen.uuid());
                        purchaseOrderFile.setCreateDate(new Date());
                        purchaseOrderFile.setNodeId(tbPurchaseOrder.getNodeId());
                        purchaseOrderFile.setDataId(tbPurchaseOrder.getId());
//                    purchaseOrderFile.setPurchaseOrderId(tbPurchaseOrder.getId());
//                    purchaseOrderFile.setPurchaseApplyId(tbPurchaseOrder.getPurchaseApplyId());
                        purchaseOrderFile.setCreateBy(tbPurchaseOrder.getCreateBy());
                        purchaseOrderFile.setUpdateBy(tbPurchaseOrder.getCreateBy());
                        purchaseOrderFile.setUpdateDate(new Date());
                    }
                    boolean b = tbPurchaseOrderFileService.saveBatch(purchaseOrderFileList);
                    if (!b) {
                        log.error("保存采购订单文件出错");
                        throw new Exception("保存采购订单文件出错");
                    }
                }

                // 采购询价单文件
                List<TbPurchaseOrderFile> purchaseEnquiryFileList = tbPurchaseOrder.getPurchaseEnquiryFile();
                if (!purchaseEnquiryFileList.isEmpty()) {
                    for (TbPurchaseOrderFile purchaseEnquiryFile : purchaseEnquiryFileList) {
                        purchaseEnquiryFile.setId(IdGen.uuid());
                        purchaseEnquiryFile.setCreateDate(new Date());
                        purchaseEnquiryFile.setNodeId(tbPurchaseOrder.getNodeId());
                        purchaseEnquiryFile.setDataId(tbPurchaseOrder.getId());
//                    purchaseEnquiryFile.setPurchaseOrderId(tbPurchaseOrder.getId());
//                    purchaseEnquiryFile.setPurchaseApplyId(tbPurchaseOrder.getPurchaseApplyId());
                        purchaseEnquiryFile.setCreateBy(tbPurchaseOrder.getCreateBy());
                        purchaseEnquiryFile.setUpdateBy(tbPurchaseOrder.getCreateBy());
                        purchaseEnquiryFile.setUpdateDate(new Date());
                    }
                    boolean b = tbPurchaseOrderFileService.saveBatch(purchaseEnquiryFileList);
                    if (!b) {
                        log.error("保存采购询价单文件出错");
                        throw new Exception("保存采购询价单文件出错");
                    }
                }
            }

        } catch (Exception e) {
            log.error(e.getMessage());
            throw e;
        }
    }

    private void deltPurchaseOrder(String id) {
        tbPurchaseOrderMapper.delByTaskId(id);
//        tbPurchaseOrderGoodsMapper.delByOrderId(id);
//        tbPurchaseOrderFileMapper.delByOrderId(id);
    }

    /**
     * 处理采购订单生成流程
     *
     * @author 苏小林
     * @date 2020/4/29 9:57
     * @param: approvalQuery
     */
//    private String handleOrderProcess(PurchaseOrderQuerySms approvalQuery) throws Exception {
//        String nodeName = "";
//        // 数据id
//        String dataId = approvalQuery.getDataId();
//        // 采购申请id
//        String purchaseApplyId = approvalQuery.getPurchaseApplyId();
//        // 下一个节点审核用户角色
//        Object roleIds = approvalQuery.getRoleIds();
//        // 登录用户id
//        String createBy = approvalQuery.getCreateBy();
//        // 节点id
//        String nodeId = approvalQuery.getNodeId();
//
//        String type = approvalQuery.getProcessType();
//        // 流程申请用户id
//        String proposerId = approvalQuery.getProposerId();
//        // 状态
//        Integer status = approvalQuery.getStatus(); // 对应节点表
//        try {
//            // 查询下一节点
//            Map<String, Object> map = getNextNode(nodeId, status,type);
//            Object nextNodeId = map.get("next_node_id");
//
//            // 查询下一个节点的下一个节点名称
//            String id = String.valueOf(map.get("nextId"));
//            TbPurchaseProcessNode nextNode = tbPurchaseProcessNodeService.getById(id);
//            if (!Objects.isNull(nextNodeId) && StringUtils.isNotBlank(nextNodeId)) {
//                // 角色
//                if (!Objects.isNull(roleIds)) {
//                    List<String> split1 = JSONArray.parseArray(String.valueOf(roleIds), String.class);
//                    for (String s : split1) {
//                        // 添加正在执行任务
//                        TbPurchaseProcessTask tbPurchaseProcessTask =
//                                new TbPurchaseProcessTask(
//                                        "", s, "", dataId, String.valueOf(nextNodeId), createBy, proposerId,type);
//                        boolean saveTask = this.save(tbPurchaseProcessTask);
//                        if (!saveTask) {
//                            log.error("保存数据失败");
//                            throw new Exception("保存数据失败");
//                        }
//
//                        TbPurchaseProcessHiTask tbPurchaseProcessHiTask =
//                                new TbPurchaseProcessHiTask(
//                                        "", dataId, String.valueOf(nextNodeId), 2, proposerId, createBy,type);
//                        boolean saveHiTask = tbPurchaseProcessHiTaskService.save(tbPurchaseProcessHiTask);
//                        if (!saveHiTask) {
//                            log.error("保存数据失败");
//                            throw new Exception("保存数据失败");
//                        }
//                    }
//                }
//            }
//
//            // todo  一个采购申请可能会有多个采购订单  所以创建采购订单的时候不修改当前任务的状态
//            // 修改目前执行的任务
////            TbPurchaseProcessHiTask tbPurchaseProcessHiTask = new TbPurchaseProcessHiTask();
////            tbPurchaseProcessHiTask.setUserId(createBy);
////            tbPurchaseProcessHiTask.setDataId(purchaseApplyId);
////            tbPurchaseProcessHiTask.setNodeId(nodeId);
////            tbPurchaseProcessHiTask.setUpdateBy(createBy);
////            tbPurchaseProcessHiTask.setUpdateDate(new Date());
////            tbPurchaseProcessHiTask.setStatus(0); // 审核通过
////            if (status == 1) {
////                tbPurchaseProcessHiTask.setStatus(1); // 审核退回
////            }
////            QueryWrapper<TbPurchaseProcessHiTask> queryWrapper = new QueryWrapper<>();
////            queryWrapper.eq("data_id",purchaseApplyId);
////            queryWrapper.eq("node_id",nodeId);
////            queryWrapper.eq("status",2);
////            TbPurchaseProcessHiTask one = tbPurchaseProcessHiTaskService.getOne(queryWrapper);
////            int row = tbPurchaseProcessHiTaskService.updateHiTask(tbPurchaseProcessHiTask);
////            if (row == 0) {
////                log.error("修改数据失败");
////                throw new Exception("修改数据失败");
////            }
////
////            int row1 = dao.deleteTask(purchaseApplyId, nodeId);
////            if (row1 == 0) {
////                log.error("删除数据失败");
////                throw new Exception("删除数据失败");
////            }
//
//            nodeName = nextNode.getNodeName();
//        } catch (Exception e) {
//            log.error("添加流程失败", e);
//            throw new Exception(e);
//        }
//        return nodeName;
//    }

    //修改支付申请表审核状态 0审核通过 1审核退回 2未审核
    public boolean updateOrderPaymentAuditStatus(Map<String, Object> data) throws Exception {
        TbPurchaseSubtaskPaymentApply tbPurchaseOrderPaymentApply = new TbPurchaseSubtaskPaymentApply();
        tbPurchaseOrderPaymentApply.setId(String.valueOf(data.get("payMentId")));
        tbPurchaseOrderPaymentApply.setUpdateDate(new Date());
        tbPurchaseOrderPaymentApply.setUpdateBy(String.valueOf(data.get("createBy")));
        tbPurchaseOrderPaymentApply.setAuditStatus(StringUtils.toInteger(data.get("auditStatus")));
        boolean b = false;
        if (tbPurchaseOrderPaymentApply.getAuditStatus() == 1) {
            int i = tbPurchaseSubtaskPaymentApplyService.delById(tbPurchaseOrderPaymentApply.getId());
            if (i > 0) {
                b = true;
            }
        } else {
            b = tbPurchaseSubtaskPaymentApplyService.updateById(tbPurchaseOrderPaymentApply);
        }

        if (!b) {
            log.error("修改支付申请表审核状态失败");
            throw new Exception("修改支付申请表审核状态失败");
        }
        return true;
    }

    public boolean updateOrderPaymentAuditStatusContract(Map<String, Object> data) throws Exception {
        TbPurchaseSubtaskPaymentApply tbPurchaseOrderPaymentApply = new TbPurchaseSubtaskPaymentApply();
        tbPurchaseOrderPaymentApply.setId(String.valueOf(data.get("payMentId")));
        tbPurchaseOrderPaymentApply.setUpdateDate(new Date());
        tbPurchaseOrderPaymentApply.setUpdateBy(String.valueOf(data.get("createBy")));
        tbPurchaseOrderPaymentApply.setAuditStatus(StringUtils.toInteger(data.get("auditStatus")));
        if (!tbPurchaseSubtaskPaymentApplyService.updateById(tbPurchaseOrderPaymentApply)) {
            log.error("修改支付申请表审核状态失败");
            throw new Exception("修改支付申请表审核状态失败");
        }
        return true;
    }

    //增加支付记录
    public boolean saveOrderPaymentRecord(Map<String, Object> data) throws Exception {
        TbPurchaseSubtaskPaymentRecord tbPurchaseOrderPaymentRecord = StringUtils.toJavaBean(data, TbPurchaseSubtaskPaymentRecord.class);
        tbPurchaseOrderPaymentRecord.setDataId(String.valueOf(data.get("dataId")));
        tbPurchaseOrderPaymentRecord.setUpdateBy(String.valueOf(data.get("createBy")));
        if (!tbPurchaseSubtaskPaymentRecordService.save(tbPurchaseOrderPaymentRecord)) {
            log.error("保存到付费申请表失败");
            throw new Exception("保存到付费申请表失败");
        }
        return true;

    }

    //保存到采购订单-采购订单其他文件
    public boolean saveOrderOtherFile(CheckPurchaseListSmsApprovalQuery checkPurchaseListApprovalQuery) throws Exception {
        List<PurchaseOrderOtherFileQuery> purchaseOrderOtherFileQueryList = checkPurchaseListApprovalQuery.getPurchaseOrderOtherFileQuery();
        if (StringUtils.isNotBlank(purchaseOrderOtherFileQueryList)) {
            if (purchaseOrderOtherFileQueryList.size() != 0) {
                Date updateDate = new Date();
                for (PurchaseOrderOtherFileQuery purchaseOrderOtherFileQuery : purchaseOrderOtherFileQueryList) {
                    TbPurchaseSubtaskOtherFile tbPurchaseOrderOtherFile =
                            StringUtils.toJavaBean(purchaseOrderOtherFileQuery, TbPurchaseSubtaskOtherFile.class);
                    tbPurchaseOrderOtherFile.setNodeId(checkPurchaseListApprovalQuery.getNodeId());
                    tbPurchaseOrderOtherFile.setDataId(checkPurchaseListApprovalQuery.getDataId());
                    tbPurchaseOrderOtherFile.setUpdateBy(checkPurchaseListApprovalQuery.getCreateBy());
                    tbPurchaseOrderOtherFile.setUpdateDate(updateDate);
                    tbPurchaseOrderOtherFile.setType(checkPurchaseListApprovalQuery.getType());
                    if (StringUtils.isBlank(tbPurchaseOrderOtherFile.getId())) {
                        tbPurchaseOrderOtherFile.setCreateDate(updateDate);
                        tbPurchaseOrderOtherFile.setCreateBy(checkPurchaseListApprovalQuery.getCreateBy());
                    }
                    if (!tbPurchaseSubtaskOtherFileService.save(tbPurchaseOrderOtherFile)) {
                        log.error("保存到付费申请表失败");
                        throw new Exception("保存到付费申请表失败");
                    }
                }
            }
        }
        return true;
    }

    //保存到采购订单任务子任务-质检记录
    public boolean saveOrderQualityRecord(CheckPurchaseRecordSmsApprovalQuery data) throws Exception {
        List<TbPurchaseSubtaskQualityRecord> tbPurchaseSubtaskQualityRecordList = data.getTbPurchaseSubtaskQualityRecordList();
        Date updateDate = new Date();
        int totalBackNumber = data.getTotalBackNumber();
        int currentBackNumber = data.getCurrentBackNumber();
        int totalInStorageNumber = data.getTotalInstorageNumber();
        for (TbPurchaseSubtaskQualityRecord purchaseOrderQualityRecord : tbPurchaseSubtaskQualityRecordList
        ) {
            purchaseOrderQualityRecord.setRemarks(data.getRemarks());
            purchaseOrderQualityRecord.setPurchaseTaskId(data.getPurchaseTaskId());
            purchaseOrderQualityRecord.setPurchaseOrderId(data.getPurchaseOrderId());
            purchaseOrderQualityRecord.setPurchaseSubtaskId(data.getDataId());
            purchaseOrderQualityRecord.setUpdateDate(updateDate);
            purchaseOrderQualityRecord.setCreateDate(updateDate);
            purchaseOrderQualityRecord.setCreateBy(data.getCreateBy());
            purchaseOrderQualityRecord.setUpdateBy(data.getCreateBy());
            purchaseOrderQualityRecord.setBatch(data.getQualityRecordBatch());
            if (!tbPurchaseSubtaskQualityRecordService.save(purchaseOrderQualityRecord)) {
                log.error("保存质检记录表失败");
                throw new Exception("保存到质检记录表失败");
            }

            if (purchaseOrderQualityRecord.getSpecialNumber() != 0) {
                data.setBadRecords(1);
            }
            if ((purchaseOrderQualityRecord.getGoodNumber() != 0 || purchaseOrderQualityRecord.getSpecialNumber() != 0)
                    && StringUtils.isNull(data.getRoleIds())) {
                // 获取归口部门领导仓管
                Set<String> roleListByRoleName = new HashSet<>();
                List<String> roleKeyNameList = new ArrayList<>();
                roleKeyNameList.add(warehouseManager);
                roleListByRoleName = tbGlobalUserMapper.getRoleListByRoleKeyName(roleKeyNameList);
                Map<Integer, Object> roleIds = new HashMap<>();
                roleIds.put(0, roleListByRoleName);
                data.setRoleIds(roleIds);
            }
            if ((purchaseOrderQualityRecord.getBackNumber() != 0 || purchaseOrderQualityRecord.getReturnNumber() != 0)
                    && StringUtils.isNull(data.getUserId())) {
                Map<Integer, Object> userId = new HashMap<>();
                userId.put(6, Arrays.asList(data.getProposerId().split(",")));
                data.setUserId(userId);
                data.setBadRecords(1);
            }
            //当前退回
            currentBackNumber = currentBackNumber + purchaseOrderQualityRecord.getBackNumber();
            //退货总数量
            totalBackNumber = totalBackNumber + purchaseOrderQualityRecord.getBackNumber();
            //入库数
            totalInStorageNumber = totalInStorageNumber + purchaseOrderQualityRecord.getGoodNumber() + purchaseOrderQualityRecord.getSpecialNumber();
        }
        data.setCurrentBackNumber(currentBackNumber);
        data.setTotalBackNumber(totalBackNumber);
        data.setTotalInstorageNumber(totalInStorageNumber);
        //采购订单任务子任务-保存质检记录文件
        saveSubtaskQualityRecordFile(data);
        return true;
    }


    //采购订单任务子任务-保存入库记录文件
    public boolean saveSubtaskStorageRecordFile(StorageSmsApprovalQuery data) throws Exception {
        List<TbPurchaseSubtaskStorageRecordFile> purchaseOrderOtherFileQuery = data.getPurchaseOrderOtherFileQuery();
        if (StringUtils.isNotBlank(purchaseOrderOtherFileQuery)) {
            for (TbPurchaseSubtaskStorageRecordFile file : purchaseOrderOtherFileQuery) {
                file.setNodeId(data.getNodeId());
                file.setDataId(data.getDataId());
                file.setStorageRecordBatch(data.getStorageRecordBatch());
                file.setCreateBy(data.getCreateBy());
                file.setUpdateBy(data.getCreateBy());
                file.setCreateDate(new Date());
                file.setUpdateDate(new Date());
                if (!tbPurchaseSubtaskStorageRecordFileService.save(file)) {
                    log.error("保存质检记录文件表失败");
                    throw new Exception("保存到质检记录文件表失败");
                }
            }
        }
        return true;
    }

    //采购订单任务子任务-保存质检记录文件
    public boolean saveSubtaskQualityRecordFile(CheckPurchaseRecordSmsApprovalQuery data) throws Exception {
        List<TbPurchaseSubtaskQualityRecordFile> purchaseOrderOtherFileQuery = data.getPurchaseOrderOtherFileQuery();
        if (StringUtils.isNotBlank(purchaseOrderOtherFileQuery)) {
            for (TbPurchaseSubtaskQualityRecordFile tbPurchaseOrderQualityRecordFile : purchaseOrderOtherFileQuery) {
                tbPurchaseOrderQualityRecordFile.setNodeId(data.getNodeId());
                tbPurchaseOrderQualityRecordFile.setDataId(data.getDataId());
                tbPurchaseOrderQualityRecordFile.setQualityRecordBatch(data.getQualityRecordBatch());
                tbPurchaseOrderQualityRecordFile.setCreateBy(data.getCreateBy());
                tbPurchaseOrderQualityRecordFile.setUpdateBy(data.getCreateBy());
                tbPurchaseOrderQualityRecordFile.setCreateDate(new Date());
                tbPurchaseOrderQualityRecordFile.setUpdateDate(new Date());
                if (!tbPurchaseSubtaskQualityRecordFileService.save(tbPurchaseOrderQualityRecordFile)) {
                    log.error("保存质检记录文件表失败");
                    throw new Exception("保存到质检记录文件表失败");
                }
            }
        }
        return true;
    }

    //采购订单-入库记录
    public Message saveOrderStorageRecord(StorageSmsApprovalQuery data) throws Exception {
        List<TbPurchaseSubtaskStorageRecord> tbPurchaseOrderStorageRecordList = data.getTbPurchaseOrderStorageRecordList();
        Date updateDate = new Date();
//        int totalInstorageNumber = data.getTotalInstorageNumber();
        for (TbPurchaseSubtaskStorageRecord purchaseOrderStorageRecord : tbPurchaseOrderStorageRecordList) {
            //判断与数据库中的待入库量是否对应
            int waitStorageNumber = tbPurchaseSubtaskQualityRecordService.getWaitStorageNumber(data.getDataId(),
                    purchaseOrderStorageRecord.getPurchaseSubtaskListId());
            if (waitStorageNumber != purchaseOrderStorageRecord.getInStorageNumber()) {
                log.error("与数据库中的待入库量不对应");
                return Message.error(1, "与待入库量不对应请重新提交");
            }

            purchaseOrderStorageRecord.setPurchaseTaskId(data.getPurchaseTaskId());
            purchaseOrderStorageRecord.setPurchaseOrderId(data.getPurchaseOrderId());
            purchaseOrderStorageRecord.setPurchaseSubtaskId(data.getDataId());
            purchaseOrderStorageRecord.setUpdateDate(updateDate);
            purchaseOrderStorageRecord.setCreateDate(updateDate);
            purchaseOrderStorageRecord.setCreateBy(data.getCreateBy());
            purchaseOrderStorageRecord.setUpdateBy(data.getCreateBy());
            purchaseOrderStorageRecord.setBatch(data.getStorageRecordBatch());
            if (!tbPurchaseSubtaskStorageRecordService.save(purchaseOrderStorageRecord)) {
                log.error("保存入库记录失败");
                throw new Exception("保存到入库记录失败");
            }
//            totalInstorageNumber=totalInstorageNumber+purchaseOrderStorageRecord.getInStorageNumber();
        }
//        data.setTotalInstorageNumber(totalInstorageNumber);
        return Message.success("成功");
    }

    //保存采购订单-退货记录/退换记录文件
    public boolean saveOrderReturnRecord(ReturnAndExchangeQuerySms data) throws Exception {
        List<TbPurchaseSubtaskReturnRecord> tbPurchaseOrderReturnRecordList = data.getTbPurchaseOrderReturnRecordList();
        Date updateDate = new Date();
        int currentReturnNumber = data.getCurrentReturnNumber();
        for (TbPurchaseSubtaskReturnRecord purchaseOrderReturnRecord :
                tbPurchaseOrderReturnRecordList) {
            purchaseOrderReturnRecord.setPurchaseTaskId(data.getPurchaseTaskId());
            purchaseOrderReturnRecord.setPurchaseOrderId(data.getPurchaseOrderId());
            purchaseOrderReturnRecord.setPurchaseSubtaskId(data.getDataId());
            purchaseOrderReturnRecord.setCreateDate(updateDate);
            purchaseOrderReturnRecord.setUpdateDate(updateDate);
            purchaseOrderReturnRecord.setCreateBy(data.getCreateBy());
            purchaseOrderReturnRecord.setUpdateBy(data.getCreateBy());
            if (!tbPurchaseSubtaskReturnRecordService.save(purchaseOrderReturnRecord)) {
                log.error("保存退货记录失败");
                throw new Exception("保存到退货记录失败");
            }

            //保存退换记录文件
            List<TbPurchaseSubtaskReturnRecordFile> tbPurchaseOrderReturnRecordFileList = purchaseOrderReturnRecord.getTbPurchaseOrderReturnRecordFileList();
            for (TbPurchaseSubtaskReturnRecordFile file : tbPurchaseOrderReturnRecordFileList) {
                file.setReturnRecordId(purchaseOrderReturnRecord.getId());
                file.setNodeId(data.getNodeId());
                file.setCreateDate(updateDate);
                file.setUpdateDate(updateDate);
                file.setCreateBy(data.getCreateBy());
                file.setUpdateBy(data.getCreateBy());
                if (!tbPurchaseSubtaskReturnRecordFileService.save(file)) {
                    log.error("保存退货记录文件失败");
                    throw new Exception("保存到退货记录文件失败");
                }
            }
            currentReturnNumber = currentReturnNumber + purchaseOrderReturnRecord.getReturnNumber();
        }
        data.setCurrentReturnNumber(currentReturnNumber);
        return true;
    }

    //修改入库的状态
    public boolean updateGoodsStorageStatus(Map<String, Object> data) throws Exception {
        TbPurchaseOrderGoods orderGoods = new TbPurchaseOrderGoods();
        orderGoods.setId(String.valueOf(data.get("purchaseGoodsId")));
        orderGoods.setStorageStatus(StringUtils.toInteger("storageStatus"));
        orderGoods.setUpdateDate(new Date());
        orderGoods.setUpdateBy(String.valueOf(data.get("createBy")));
//        QueryWrapper wrapper=new QueryWrapper<>();
//        wrapper.eq("purchase_apply_id",String.valueOf(data.get("purchaseApplyId")));
//        wrapper.eq("purchase_order_id",String.valueOf(data.get("dataId")));
//          tbPurchaseOrderGoodsService.update(orderGoods,wrapper)
        if (!tbPurchaseOrderGoodsService.updateById(orderGoods)) {
            log.error("修改入库的状态失败");
            throw new Exception("修改入库的状态失败");
        }
        return true;
    }

    //保存终止合同回执文件
    public boolean saveReturnFile(TerminationContractReturnFileQuerySms terminationContractReturnFileQuery) throws Exception {
        //先删除后添加
        tbPurchaseTerminationContractApplyFileService.removeFile(terminationContractReturnFileQuery.getContractId());
        //获取最新终止合同记录
        List<TbPurchaseTerminationContractApplyFile> tbPurchaseTerminationContractRecordFileList = terminationContractReturnFileQuery.getTbPurchaseTerminationContractRecordFileList();
        if (tbPurchaseTerminationContractRecordFileList.size() != 0) {
            Date updateDate = new Date();
            for (TbPurchaseTerminationContractApplyFile file : tbPurchaseTerminationContractRecordFileList) {
                file.setId("");
                file.setTerminationContractId(terminationContractReturnFileQuery.getContractId());
                file.setUpdateBy(terminationContractReturnFileQuery.getCreateBy());
                file.setUpdateDate(updateDate);
                file.setCreateDate(updateDate);
                file.setCreateBy(terminationContractReturnFileQuery.getCreateBy());
                if (!tbPurchaseTerminationContractApplyFileService.save(file)) {
                    log.error("保存到付费申请表失败");
                    throw new Exception("保存到付费申请表失败");
                }
            }
        }
        return true;
    }

    //供应链部付款方式，采购合同
    public boolean payContractApproval(PayContractQuerySms data) throws Exception {
        //流程
        this.execProcessOrder(data);
        //保存到订单表中
        this.saveUpdatePurchaseOrder(data);
        //计算支付金额
        BigDecimal totalMoney = data.getTotalMoney();
        Integer advanceProportion = data.getAdvanceProportion();
        String mul = StringUtils.mul(totalMoney, advanceProportion,2);
        data.setPaymentMoney(new BigDecimal(mul));
        //保存支付申请表
        UploadContractFileQuerySms uploadContractFileQuery = StringUtils.toJavaBean(data, UploadContractFileQuerySms.class);
        this.savePayApproval(uploadContractFileQuery);
        //保存合同上传
        data.setType(3);
        return this.saveContractApproval(data);
    }

    //供应链部内签合同会签合同上传合同文件
    public boolean uploadContractFileApproval(UploadContractFileQuerySms data) throws Exception {
        //流程
        this.execProcessOrderSubtask(data);
        //保存付款申请
        if (data.getSubmitStatus() == 2) {
            //计算支付金额
            BigDecimal totalMoney = data.getTotalMoney();
            Integer advanceProportion = data.getProportion();
            String mul = StringUtils.mul(totalMoney, advanceProportion,2);
            data.setPaymentMoney(new BigDecimal(StringUtils.div(mul, 100, 2)));
            //保存支付申请表
            this.savePayApproval(data);
        }
        PayContractQuerySms payContractQuery = StringUtils.toJavaBean(data, PayContractQuerySms.class);
        //保存合同上传
        payContractQuery.setType(3);
        return this.saveContractApproval(payContractQuery);
    }

    // 退换
    public boolean returnAndExchangeApproval(ReturnAndExchangeQuerySms data) throws Exception {
        //保存采购订单任务子任务-退换记录/退换记录文件
        this.saveOrderReturnRecord(data);
        //当前有没有正在执行的流程
        //当无入库数全部退换 订单结束
        //有入库数  当前退换数为0 时 和判断入库流程是否存在   若存在 直接删除退货流程 不存在 判断支付方式 1 订单结束  2二期款申请
        //有入库数  当前退换数大于0 时  到质检
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("data_id", data.getDataId());
        queryWrapper.notIn("node_id", data.getNodeId());
        List list = dao.selectList(queryWrapper);
        //流程指派人
        if (data.getTotalNumber() == 0
                || (data.getTotalNumber() > 0 && data.getCurrentReturnNumber() == 0 && list.size() == 0 && data.getPaymentWay() == 1)) { //订单结束
            data.setStatus(1);
            //流程
            this.execProcessOrderSubtask(data);
            Thread.sleep(1000);
            TbPurchaseProcessHiTask tbPurchaseProcessHiTask = new TbPurchaseProcessHiTask("", data.getDataId(), "3812CE6C40334DCDAE35DC5E5621B887", 0, data.getProposerId(), data.getCreateBy(), "2");
            this.saveProcessHiTask(tbPurchaseProcessHiTask);
        } else if (data.getTotalNumber() > 0 && data.getCurrentReturnNumber() == 0 && list.size() == 0 && data.getPaymentWay() == 2) { //二期款申请
            data.setStatus(12);
            //采购文件编写员
            data.setUserId(Arrays.asList(data.getProposerId().split(",")));
            //流程
            this.execProcessOrderSubtask(data);
        } else if (data.getTotalNumber() > 0 && data.getCurrentReturnNumber() > 0) { //质检
            // 获取归口部门领导
            List<String> deptLeader = tbGlobalUserService.getDeptLeader(String.valueOf(data.getRelevantDeptId()));
            data.setUserId(deptLeader);
            data.setStatus(0);
            //流程
            this.execProcessOrderSubtask(data);

        } else if (data.getTotalNumber() > 0 && data.getCurrentReturnNumber() == 0 && list.size() != 0) {
            //删除正在执行的流程和保存历史记录
            data.setProcessType("2");
            Map mapParam = StringUtils.toJavaBean(data, Map.class);
            this.deleteHandleAuditAndSaveHi(mapParam);
            this.updatePurchaseOrderSubtaskSubmitStatus(data, "入库");
        } else {
            log.error("工单异常");
            throw new Exception("工单异常");
        }

        //获取送样次数
        int counts = tbPurchaseSubtaskReturnRecordService.getCounts(data.getDataId());
        //修改送样次数
        TbPurchaseOrderSubtask tbPurchaseOrderSubtask = new TbPurchaseOrderSubtask();
        tbPurchaseOrderSubtask.setId(data.getDataId());
        tbPurchaseOrderSubtask.setSampleDeliveryTimes(counts);
        if (!tbPurchaseOrderSubtaskService.updateById(tbPurchaseOrderSubtask)) {
            log.error("修改送样次数失败");
            throw new Exception("修改送样次数失败");
        }
        return true;
    }

    //    发起商务协调
    public boolean businessNegotiationApproval(String dataId, int businessNegotiation) {
        TbPurchaseOrderSubtask tbPurchaseOrderSubtask = new TbPurchaseOrderSubtask();
        tbPurchaseOrderSubtask.setId(dataId);
        tbPurchaseOrderSubtask.setBusinessNegotiation(businessNegotiation);
        return tbPurchaseOrderSubtaskService.updateById(tbPurchaseOrderSubtask);
    }

    //     期款申请
    public boolean installmentApproval(PaymentQuerySms data) throws Exception {
        //流程
        this.execProcessOrderSubtask(data);
        //保存单据说明
        data.setType(6);
        CheckPurchaseListSmsApprovalQuery checkPurchaseListApprovalQuery = StringUtils.toJavaBean(data, CheckPurchaseListSmsApprovalQuery.class);
        this.saveOrderOtherFile(checkPurchaseListApprovalQuery);
//        if(StringUtils.isNotBlank(data.getBadRecords())){
//            //修改订单表bad_records 物料不良记录 0无 1有
//            TbPurchaseOrder tbPurchaseOrder = new TbPurchaseOrder();
//            tbPurchaseOrder.setId(data.getDataId());
//            tbPurchaseOrder.setBadRecords(data.getBadRecords());
//            if(!tbPurchaseOrderService.updateById(tbPurchaseOrder)){
//                log.error("期款申请修改订单表失败");
//                throw new Exception("期款申请修改订单表失败");
//            }
//        }
        //保存支付申请表
        if (StringUtils.isBlank(data.getPaymentMoney())) {
            //计算支付金额
            BigDecimal totalMoney = data.getTotalMoney();
            Integer installmentProportion = data.getInstallmentProportion();
            String mul = StringUtils.mul(totalMoney, installmentProportion,2);
            data.setPaymentMoney(new BigDecimal(StringUtils.div(mul, 100, 2)));
        }
        UploadContractFileQuerySms uploadContractFileQuery = StringUtils.toJavaBean(data, UploadContractFileQuerySms.class);
        this.savePayApproval(uploadContractFileQuery);
        return true;

    }

    //发起终止合同
    public boolean terminationContractApproval(TerminationContractSmsApprovalQuery data) throws Exception {
        data.setProcessType("3");
        TbPurchaseOrderSubtask tbPurchaseOrderSubtask = new TbPurchaseOrderSubtask();
        tbPurchaseOrderSubtask.setSubmitStatus(data.getSubmitStatus());
        tbPurchaseOrderSubtask.setId(data.getDataId());
        tbPurchaseOrderSubtask.setTerminationContract(data.getTerminationContract());
        if (!tbPurchaseOrderSubtaskService.updateById(tbPurchaseOrderSubtask)) {
            log.error("发起终止合同修改订单表失败");
            throw new Exception("发起终止合同修改订单表失败");
        }
        //保存终止合同申请
        Date date = new Date();
        if (data.getTerminationContract() == 1) {
            TbPurchaseTerminationContractApply tbPurchaseTerminationContractRecord = new TbPurchaseTerminationContractApply();
            tbPurchaseTerminationContractRecord.setNodeName("终止合同");
            tbPurchaseTerminationContractRecord.setPurchaseTaskId(data.getPurchaseTaskId());
            tbPurchaseTerminationContractRecord.setPurchaseSubtaskId(data.getDataId());
            tbPurchaseTerminationContractRecord.setCreateDate(date);
            tbPurchaseTerminationContractRecord.setCreateBy(data.getCreateBy());
            tbPurchaseTerminationContractRecord.setUpdateDate(date);
            tbPurchaseTerminationContractRecord.setUpdateBy(data.getCreateBy());
            if (!tbPurchaseTerminationContractApplyService.save(tbPurchaseTerminationContractRecord)) {
                log.error("保存终止合同记录失败");
                throw new Exception("保存终止合同记录失败");
            }
            data.setDataId(tbPurchaseTerminationContractRecord.getId());
            //流程
            Map<String, Object> mapParam = JSON.parseObject(JSON.toJSONString(data), Map.class);
            String s = this.startContractProcess(mapParam);
            //修改终止合同节点
            TbPurchaseTerminationContractApply tbPurchaseTerminationContractApply = new TbPurchaseTerminationContractApply();
            tbPurchaseTerminationContractApply.setId(tbPurchaseTerminationContractRecord.getId());
            tbPurchaseTerminationContractApply.setNodeName(s);
            if (tbPurchaseTerminationContractApplyMapper.updateById(tbPurchaseTerminationContractApply) != 1) {
                log.error("修改终止合同节点失败");
                throw new Exception("修改终止合同节点失败");
            }
        } else {
            //删除流程
            int row2 = dao.deleteTaskByDataId(String.valueOf(data.getDataId()));
            if (row2 == 0) {
                log.error("删除流程失败");
                throw new Exception("删除流程失败");
            }
        }
        return true;
    }

    // 终止合同回传文件
    public boolean terminationContractReturnFileApproval(TerminationContractReturnFileQuerySms data) throws Exception {
        //保存终止合同回传文件
        data.setContractId(data.getDataId());
        this.saveReturnFile(data);
        if (data.getSubmitStatus() == 2) {
            data.setDataId(data.getDataId());
            data.setProcessType("3");
            //保存支付申请表
            if (data.getPayMentType() == 1) {
                data.setPaymentMoney(data.getPaymentMoney().negate());
            }
            UploadContractFileQuerySms uploadContractFileQuery = StringUtils.toJavaBean(data, UploadContractFileQuerySms.class);
            this.savePayApproval(uploadContractFileQuery);
            // 流程
            this.execProcessContract(data);
            //删除结算信息
            tbPurchaseSubtaskStatementService.deleteStatementByDataId(data.getPurchaseOrderId());
            //保存结算信息
            TbPurchaseSubtaskStatement tbPurchaseSubtaskStatement = StringUtils.toJavaBean(data, TbPurchaseSubtaskStatement.class);
            tbPurchaseSubtaskStatement.setDataId(data.getPurchaseOrderId());
            tbPurchaseSubtaskStatement.setContractTotalMoney(data.getTotalMoney());
            tbPurchaseSubtaskStatement.setUpdateBy(data.getCreateBy());
            tbPurchaseSubtaskStatement.setType(data.getPayMentType());
            this.saveStatement(tbPurchaseSubtaskStatement);
        }
        return true;
    }

    //保存结算信息
    public boolean saveStatement(TbPurchaseSubtaskStatement tbPurchaseSubtaskStatement) throws Exception {
        if (!tbPurchaseSubtaskStatementService.save(tbPurchaseSubtaskStatement)) {
            log.error("保存结算单失败");
            throw new Exception("保存结算单失败");
        }
        return true;
    }

    //财务终止合同付款
    public boolean financeContractPayApproval(EndOrderQuerySms data) throws Exception {
        data.setProcessType("3");
        //流程
        CloseOrderQuery closeOrderQuery = StringUtils.toJavaBean(data, CloseOrderQuery.class);
        this.execProcessCloseContract(closeOrderQuery);
        return true;
    }

    public boolean uploadContractBillOfCredit(EndOrderQuerySms data) throws Exception {
        data.setProcessType("3");
        // 保存到采购订单-采购订单其他文件付款
        data.setType(4);
        this.saveOrderOtherFile(data);
        //修改支付申请表
        TbPurchaseSubtaskPaymentApply newPayMentApply = tbPurchaseSubtaskPaymentApplyService.getNewPayMentApply(data.getDataId());
        data.setPayMentId(newPayMentApply.getId());
        Map<String, Object> mapParam = StringUtils.toJavaBean(data, Map.class);
        this.updateOrderPaymentAuditStatus(mapParam);
        // 保存支付记录
        if (data.getSubmitStatus() == 2) {
            this.saveOrderPaymentRecord(mapParam);
        }

        // 查询财务主管
        Long roleId = tbGlobalUserMapper.getRoleIdByRoleKeyName(financialManager);
        String processTaskId = data.getProcessTaskId();
        TbPurchaseProcessTask tbPurchaseProcessTask = new TbPurchaseProcessTask();
        tbPurchaseProcessTask.setId(processTaskId);
        tbPurchaseProcessTask.setRoleId(String.valueOf(roleId));
        int i = dao.updateById(tbPurchaseProcessTask);
        if (i == 0) {
            log.error("修改审核角色失败");
            throw new Exception("修改审核角色失败");
        }
        return true;

    }

    //    总经理审批终止合同付款申请
    public boolean InstallmentApprovalPayApproval(ManagerLSValuePaySmsApprovalQuery data) throws Exception {
        //流程
        this.execProcessOrderSubtask(data);
        //修改支付申请表审核状态 0审核通过 1审核退回 2未审核
        if (data.getStatus() == 0) {
            data.setAuditStatus("0");
        } else if (data.getStatus() == 1) {
            data.setAuditStatus("1");
        }
        Map<String, Object> mapParam = StringUtils.toJavaBean(data, Map.class);
        this.updateOrderPaymentAuditStatus(mapParam);
        return true;
    }

    public boolean managerContractPayApproval(ManagerLSValuePaySmsApprovalQuery data) throws Exception {
        //流程
        data.setProcessType("3");
        this.execProcessContract(data);
        //修改支付申请表审核状态 0审核通过 1审核退回 2未审核
        if (data.getStatus() == 0) {
            data.setAuditStatus("0");
        } else if (data.getStatus() == 1) {
            data.setAuditStatus("1");
        }
        TbPurchaseSubtaskPaymentApply newPayMentApply = tbPurchaseSubtaskPaymentApplyService.getNewPayMentApply(data.getDataId());
        data.setPayMentId(newPayMentApply.getId());
        Map<String, Object> mapParam = StringUtils.toJavaBean(data, Map.class);
        this.updateOrderPaymentAuditStatus(mapParam);
        return true;
    }


    //创建人重新提交
    public boolean returnCommitApproval(ReturnCommitQuerySms data) throws Exception {
        //保存修改采购申请表
        TbPurchaseApply tbPurchaseApply = data.getTbPurchaseApply();
        String nodeId = "";
        tbPurchaseApply.setUpdateBy(data.getCreateBy());
        if (tbPurchaseApplyService.save(tbPurchaseApply)) {
            //保存采购申请清单表
            //先删后加
            int i = tbPurchaseApplyListService.removeApplyList(String.valueOf(tbPurchaseApply.getId()));
            if (tbPurchaseApply.getTbPurchaseApplyList().size() > 0) {
                List<TbPurchaseApplyList> tbPurchaseApplyList = tbPurchaseApply.getTbPurchaseApplyList();
                for (TbPurchaseApplyList applyList : tbPurchaseApplyList
                ) {
                    applyList.setCreateBy(data.getCreateBy());
                    applyList.setUpdateBy(data.getCreateBy());
                    applyList.setPurchaseApplyId(String.valueOf(tbPurchaseApply.getId()));
                    if (!tbPurchaseApplyListService.save(applyList)) {
                        throw new Exception("保存采购申请清单表失败");
                    }
                }
            }
        }
        //流程
        if (data.getSubmitStatus() == 2) {
            Map<String, Object> mapParam = StringUtils.toJavaBean(data, Map.class);
            String s = this.handleAudit(mapParam);
            tbPurchaseApply.setNodeName(s);
//            data.setNodeName(String.valueOf(mapList.get("nodeName")));
//            nodeId=String.valueOf(mapList.get("nodeId"));
            if (!tbPurchaseApplyService.updateById(tbPurchaseApply)) {
                throw new Exception("采购申请表保存节点失败");
            }
        }

        //采购申请意向或方案文件
        //根据采购申请id删除采购申请意向或方案文件
        tbPurchaseApplyFileService.removeIntentionSchemeFile(String.valueOf(tbPurchaseApply.getId()));
        List<TbPurchaseApplyFile> tbPurchaseApplyIntentionSchemeFile = tbPurchaseApply.getTbPurchaseApplyFileList();
        if (tbPurchaseApplyIntentionSchemeFile.size() > 0) {
            for (TbPurchaseApplyFile file : tbPurchaseApplyIntentionSchemeFile
            ) {
                file.setNodeId(nodeId);
                file.setCreateBy(data.getCreateBy());
                file.setUpdateBy(data.getCreateBy());
                file.setPurchaseApplyId(String.valueOf(tbPurchaseApply.getId()));
                if (!tbPurchaseApplyFileService.save(file)) {
                    throw new Exception("保存采购申请意向或方案文件失败");
                }
            }
        }
        return true;
    }

    //判断是否有归口意见
    public boolean hasDeptLeaderOpinon(String dataId, String nodeId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("data_id", dataId);
        queryWrapper.notIn("node_id", nodeId);
        List list = super.listMaps(queryWrapper);
        if (list.size() > 0) {
            return false;
        }
        return true;
    }

    /**
     * 创建人重新提交
     *
     * @author 苏小林
     * @date 2020/6/4 11:46
     * @param: data
     */
    public void resubmit(Map<String, Object> data) throws Exception {
        TbPurchaseApply tbPurchaseApply = StringUtils.toJavaBean(data, TbPurchaseApply.class);
        Boolean aBoolean = tbPurchaseApplyService.savePurchaseApply(tbPurchaseApply);
        if (aBoolean) {
            this.handleAudit(data);

        }

    }

    // 正在执行的合同审批
    public List<Map<String, Object>> getContractExcelFlowList(String dataId) {
        return dao.getContractExcelFlowList(dataId);
    }

    //关闭终止合同
    public boolean closeTerminationContractApproval(CloseTerminationContractApprovalQuery data) throws Exception {
        TbPurchaseOrderSubtask tbPurchaseOrderSubtask = new TbPurchaseOrderSubtask();
        tbPurchaseOrderSubtask.setSubmitStatus(2);
        tbPurchaseOrderSubtask.setId(data.getPurchaseOrderSubtaskId());
        tbPurchaseOrderSubtask.setTerminationContract(data.getTerminationContract());
        if (!tbPurchaseOrderSubtaskService.updateById(tbPurchaseOrderSubtask)) {
            log.error("发起终止合同修改订单任务子任务表失败");
            throw new Exception("发起终止合同修改订单任务子任务表失败");
        }
        //删除流程
        int row2 = dao.deleteTaskByDataId(String.valueOf(data.getDataId()));
        if (row2 == 0) {
            log.error("删除流程失败");
            throw new Exception("删除流程失败");
        }
        return true;
    }

    /**
     * 保存采购订单子任务
     *
     * @author 苏小林
     * @date 2020/6/11 8:57
     * @param: tbPurchaseOrderSubtask
     */
    public void saveOrderSubTask(SaveOrderSubTaskVo saveOrderSubTaskVo) throws Exception {

        TbPurchaseOrderSubtask tbPurchaseOrderSubtask = saveOrderSubTaskVo.getSubTaskData();
        // 获取合同数据
        TbContractApply contractData = saveOrderSubTaskVo.getContractData();
        if (contractData != null) {
            contractData.setSubmitStatus(2);
            contractData.setSubtaskId(IdGen.uuid());
            TbContractApply tbContractApply = tbContractApplyService.startProcess(contractData);
            // 拼接数据
            tbPurchaseOrderSubtask.setPaymentWay(tbContractApply.getPaymentWay());
            tbPurchaseOrderSubtask.setAdvanceProportion(tbContractApply.getAdvanceProportion());
            tbPurchaseOrderSubtask.setSecondProportion(tbContractApply.getSecondProportion());
            tbPurchaseOrderSubtask.setFinalProportion(tbContractApply.getFinalProportion());
            tbPurchaseOrderSubtask.setContractApplyId(tbContractApply.getId());
            tbPurchaseOrderSubtask.setId(tbContractApply.getSubtaskId());
        }


        // 计算总价格
        String total = "0.00";
        int totalNumber = 0;

        List<TbPurchaseSubtaskList> purchaseOrderGoods = tbPurchaseOrderSubtask.getPurchaseOrderGoodsList();
        if (!purchaseOrderGoods.isEmpty() && purchaseOrderGoods.size() > 0) {
            for (TbPurchaseSubtaskList tbPurchaseOrderGoods : purchaseOrderGoods) {
                total = StringUtils.add(total,StringUtils.mul(tbPurchaseOrderGoods.getPrice(), tbPurchaseOrderGoods.getApplyNumber(),2));
                totalNumber= totalNumber + tbPurchaseOrderGoods.getApplyNumber();
            }
        } else {
            throw new Exception("没有任务清单");
        }
        tbPurchaseOrderSubtask.setTotalNumber(totalNumber);
        tbPurchaseOrderSubtask.setTotalMoney(new BigDecimal(total));


        if (StringUtils.isNotBlank(tbPurchaseOrderSubtask.getId())) {
            tbPurchaseOrderSubtaskMapper.delById(tbPurchaseOrderSubtask.getId());
        }
        if (StringUtils.isBlank(tbPurchaseOrderSubtask.getPaymentWay())) {
            tbPurchaseOrderSubtask.setPaymentWay(1);
        }

        String orderSubtaskNewNum = tbPurchaseApplyService.getOrderSubtaskNewNum(tbPurchaseOrderSubtask.getDeptId(), tbPurchaseOrderSubtask.getCategory());
        if (StringUtils.isBlank(tbPurchaseOrderSubtask.getContractApplyId())) {
            tbPurchaseOrderSubtask.setId(IdGen.uuid());
        }

        tbPurchaseOrderSubtask.setSubtaskNumber(orderSubtaskNewNum);
        tbPurchaseOrderSubtask.setCreateDate(new Date());
        int insert = tbPurchaseOrderSubtaskMapper.insert(tbPurchaseOrderSubtask);
        if (insert > 0) {
            List<TbPurchaseSubtaskList> purchaseOrderGoodsList = tbPurchaseOrderSubtask.getPurchaseOrderGoodsList();
            if (purchaseOrderGoodsList != null && purchaseOrderGoodsList.size() != 0) {
                for (TbPurchaseSubtaskList tbPurchaseSubtaskList : purchaseOrderGoodsList) {
                    tbPurchaseSubtaskList.setDataId(tbPurchaseOrderSubtask.getId());
                    tbPurchaseSubtaskList.setOrderGoodsId(tbPurchaseSubtaskList.getId());
                    tbPurchaseSubtaskList.setCreateBy(tbPurchaseOrderSubtask.getCreateBy());
                    tbPurchaseSubtaskList.setCreateDate(new Date());
                    tbPurchaseSubtaskList.setUpdateBy(tbPurchaseOrderSubtask.getCreateBy());
                    tbPurchaseSubtaskList.setUpdateDate(new Date());
                    tbPurchaseSubtaskList.setId(IdGen.uuid());
                }

                tbPurchaseSubtaskListService.saveBatch(purchaseOrderGoodsList);
            }
        } else {
            log.error("保存订单子任务失败");
            throw new Exception("保存订单子任务失败");
        }

        if (!"3".equals(tbPurchaseOrderSubtask.getCategory())) {
            //保存付款申请
            this.saveLVPayApproval(tbPurchaseOrderSubtask);
        }

        // 保存采购流程
        this.startOrderSubTaskProcess(tbPurchaseOrderSubtask);

        // 修改采购订单状态
        String purchaseOrderId = tbPurchaseOrderSubtask.getPurchaseOrderId();
        TbPurchaseOrder tbPurchaseOrder = new TbPurchaseOrder();
        tbPurchaseOrder.setId(purchaseOrderId);
        tbPurchaseOrder.setDealWithStatus("已处理");
        tbPurchaseOrderService.updateById(tbPurchaseOrder);

    }

    private void startOrderSubTaskProcess(TbPurchaseOrderSubtask tbPurchaseOrderSubtask) throws Exception {


        String nodeId = "39DB703EDD0A4A20AF858FBBED6BF6ED";// 准备采购合同及付款方式
        TbPurchaseProcessHiTask tbPurchaseProcessHiTask = new TbPurchaseProcessHiTask(tbPurchaseOrderSubtask.getCreateBy(), tbPurchaseOrderSubtask.getId(), nodeId, 0, tbPurchaseOrderSubtask.getCreateBy(), tbPurchaseOrderSubtask.getCreateBy(), "2");
        tbPurchaseProcessHiTask.setCreateDate(new Date(System.currentTimeMillis() - 1000));
        this.saveProcessHiTask(tbPurchaseProcessHiTask);

        // 如果合同id为空 表示低值固资不用走合同审核，直接下一流程总经理审核付款信息
        if (StringUtils.isBlank(tbPurchaseOrderSubtask.getContractApplyId())) {
            String createBy = tbPurchaseOrderSubtask.getCreateBy();// 当前登录用户
            List<String> roleNames = tbGlobalUserMapper.getRoleKeyNamesByUserId(StringUtils.toLong(createBy));

            PurchaseOrderQuerySms approvalQuery = new PurchaseOrderQuerySms();

            if (!roleNames.contains(roleNameThree)) {//如果角色中不包含采购经理
                approvalQuery.setNodeId(nodeId);
                approvalQuery.setStatus(8); // 部门领导审核
                //查询采购经理角色列表
                List<String> roleNameList = new ArrayList<>();
                roleNameList.add(roleNameThree);
                Set<String> roleListByRoleName = tbGlobalUserMapper.getRoleListByRoleKeyName(roleNameList);
                approvalQuery.setRoleIds(roleListByRoleName);
            } else {
                approvalQuery.setStatus(10);// 总经理审核
                approvalQuery.setNodeId(nodeId);
                // 查询角色列表
                List<String> roleNameList = new ArrayList<>();
                roleNameList.add(roleNameTwo);
                Set<String> roleListByRoleName = tbGlobalUserMapper.getRoleListByRoleKeyName(roleNameList);
                approvalQuery.setRoleIds(roleListByRoleName);
            }
            approvalQuery.setDataId(tbPurchaseOrderSubtask.getId());
            approvalQuery.setProcessType("2");
            approvalQuery.setProcessTaskId(tbPurchaseOrderSubtask.getProcessTaskId());
            approvalQuery.setCreateBy(tbPurchaseOrderSubtask.getCreateBy());
            approvalQuery.setSubmitStatus(2);
            approvalQuery.setProposerId(tbPurchaseOrderSubtask.getCreateBy());

            Map<String, Object> mapParam = StringUtils.toJavaBean(approvalQuery, Map.class);
            String s = this.handleAudit(mapParam);
            tbPurchaseOrderSubtask.setNodeName(s);
            tbPurchaseOrderSubtaskMapper.updateById(tbPurchaseOrderSubtask);
            sendMessage(approvalQuery);

        } else {
            String nodeId1 = "4687484WE87643DEd23DFJH6767GF543"; // 合同审批中
            TbPurchaseProcessTask tbPurchaseProcessTask =
                    new TbPurchaseProcessTask(
                            "", "", "", tbPurchaseOrderSubtask.getId(), nodeId1, tbPurchaseOrderSubtask.getCreateBy(), tbPurchaseOrderSubtask.getCreateBy(), "2");
            tbPurchaseProcessTask.setCreateDate(new Date());
            boolean saveTask = this.save(tbPurchaseProcessTask);
            if (saveTask) {
                // 添加正在执行任务到历史任务
                if (tbPurchaseProcessTask != null) {
                    TbPurchaseProcessHiTask tbPurchaseProcessHiTask1 = new TbPurchaseProcessHiTask();
                    BeanUtils.copyProperties(tbPurchaseProcessTask, tbPurchaseProcessHiTask1);
                    tbPurchaseProcessHiTask1.setStatus(2);// 未审核
                    tbPurchaseProcessHiTask1.setUserId(tbPurchaseOrderSubtask.getCreateBy());
                    tbPurchaseProcessHiTask1.setUpdateDate(null);
                    tbPurchaseProcessHiTask1.setUpdateBy("");
                    int insert = tbPurchaseProcessHiTaskMapper.insert(tbPurchaseProcessHiTask1);
                    if (insert == 0) {
                        log.error("保存数据失败");
                        throw new Exception("保存数据失败");
                    }
                }
            } else {
                log.error("保存数据失败");
                throw new Exception("保存数据失败");
            }
            tbPurchaseOrderSubtask.setNodeName("合同审核中");
            tbPurchaseOrderSubtaskMapper.updateById(tbPurchaseOrderSubtask);

        }

        // 修改采购订单审核任务
        String purchaseOrderId = tbPurchaseOrderSubtask.getPurchaseOrderId();
        String nodeId2 = "45FD4DF5346464RT34365435H45Y4J415";// 采购中
        TbPurchaseProcessTask byDataId = dao.getByDataIdAndNodeId(purchaseOrderId, nodeId2);
        if (byDataId != null) {
            SmsApprovalQuery smsApprovalQuery = new SmsApprovalQuery();
            smsApprovalQuery.setNodeId(nodeId2);
            smsApprovalQuery.setProcessTaskId(byDataId.getId());
            smsApprovalQuery.setProcessType("1");
            Map<String, Object> map = StringUtils.toJavaBean(smsApprovalQuery, Map.class);
            handleAudit(map);
        }


    }

    private List<Object> handleReceiveUserIds(SmsApprovalQuery data) {
        List<Object> list = Lists.newArrayList();
        Object userId = data.getUserId();
        if (!Objects.isNull(userId)) {
            List<String> userIds = JSONArray.parseArray(String.valueOf(userId), String.class);
            list.addAll(userIds);
        }
        Object roleIds = data.getRoleIds();
        if (!Objects.isNull(roleIds)) {
            List<Long> roles = JSONArray.parseArray(String.valueOf(roleIds), Long.class);
            List<Long> userIds = tbGlobalUserService.getUserListByRoleIds(roles);
            list.addAll(userIds);
        }
        return list;
    }

    public void sendMessage(SmsApprovalQuery data) {
        List<Object> receiveUserIds = this.handleReceiveUserIds(data);
        // 消息发送
        Map<String, Object> messageMap = Maps.newHashMap();
        messageMap.put("projectId", 3);
        messageMap.put("dataId", data.getDataId());
        messageMap.put("title", "供应链通知");
        messageMap.put("sender", data.getCreateBy());
        messageMap.put("userIds", receiveUserIds);
        applicationContext.publishEvent(new MessageEvent(this, messageMap));
    }

    //供应链代办数
    public Integer purchaseAgencyNum(Integer userId) {
        List<String> roleList = tbGlobalUserService.getRoleListByUserId(userId);
        // 查询部门列表
        List<String> departList = tbGlobalUserMapper.getDepartIdsByUserId(userId);
        return dao.purchaseAgencyNum(userId, roleList, departList);
    }

    // 添加采购订单到任务中
    public void execPurchaseOrder(SmsApprovalQuery data) throws Exception {
        TbPurchaseProcessHiTask tbPurchaseProcessHiTask = new TbPurchaseProcessHiTask("", data.getDataId(), "45FD4DF5346464RT34365435H45Y4J415", 0, data.getProposerId(), data.getCreateBy(), "2");
        this.saveProcessHiTask(tbPurchaseProcessHiTask);

        String dataId = data.getDataId();
        List<TbPurchaseOrder> list = tbPurchaseOrderService.getPurchaseOrderByTaskId(dataId);
        for (TbPurchaseOrder tbPurchaseOrder : list) {
            //流程
            StartProcessDto startProcessDto = new StartProcessDto();
            startProcessDto.setCreateBy(data.getCreateBy());
            startProcessDto.setDataId(tbPurchaseOrder.getId());
            startProcessDto.setUserId(Arrays.asList(data.getProposerId()));
            startProcessDto.setProcessType("2");
            startProcessDto.setNodeId("45FD4DF5346464RT34365435H45Y4J415");// 采购中节点

            // 消息
            SmsApprovalQuery smsApprovalQuery = new SmsApprovalQuery();
            smsApprovalQuery.setDataId(tbPurchaseOrder.getId());
            smsApprovalQuery.setCreateBy(data.getCreateBy());
            smsApprovalQuery.setUserId(Arrays.asList(data.getProposerId()));

            try {
                this.startProcessByUserId(startProcessDto);
                this.sendMessage(smsApprovalQuery);
            } catch (Exception e) {
                log.error("流程添加出错：{}", e);
                throw e;
            }
        }
    }


}
